﻿using AutoCAD;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.DwgIndx;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.Internal;
using Autodesk.AutoCAD.Internal.Calculator;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Windows.Data;
using Autodesk.Interop.ConnectionPoint;
using Autodesk.RasterDesign.ApplicationServices;
using Autodesk.Windows.Media;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using MoreLinq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.ListBox;
using static WCAD.Jigs;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using IntegerCollection = Autodesk.AutoCAD.Geometry.IntegerCollection;
using IUtils = Autodesk.AutoCAD.DwgIndx.Utils;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;
using Polyline = Autodesk.AutoCAD.DatabaseServices.Polyline;
using Utils = Autodesk.AutoCAD.Internal.Utils;
using Viewport = Autodesk.AutoCAD.DatabaseServices.Viewport;
using StatusBar = Autodesk.AutoCAD.Windows.StatusBar;
using System.Threading;
using Autodesk.Internal.Windows;
using System.Text.Json;
using Autodesk.AutoCAD.PlottingServices;
using System.Text.RegularExpressions;

namespace WCAD
{

    public class CADCommand : IExtensionApplication
    {

        /* 各个类的功能
        CAD：文档、数据库、编辑器之类的东西
        UserControler：用户交互的功能，比如选择、输入文字数字等等
        
        */
        #region 加载插件执行
        public void Initialize()
        {
            // WCAD.Ed.WriteMessage("WCAD加载成功，输入命令WCADHelp查看所有命令");
        }

        public void Terminate()
        {
            throw new NotImplementedException();
        }
        #endregion
        //找到手拉手的直线，组成多段线
        [CommandMethod("FindConnectLines")]
        public void FindConnectLines()
        {
            if (!UmUserMethod.SelectEntities(out List<Line> lines)) return;
            var list = EmEntityMethod.GroupEntities(lines, (e1, e2) =>
            {
                if (e1 is Line && e2 is Line)
                {
                    Line l1 = (Line)e1;
                    Line l2 = (Line)e2;
                    if (l1.StartPoint == l2.StartPoint || l1.StartPoint == l2.EndPoint || l1.EndPoint == l2.StartPoint || l1.EndPoint == l2.EndPoint)
                    {
                        return true;
                    }
                }
                return false;
            });
            foreach (var entity in list)
            {
                Polyline polyline = new Polyline();
                polyline.ColorIndex = 1;
                polyline.AddVertexAt(0, entity[0].StartPoint.Convert2d(new Plane()), 0, 0, 0);
                polyline.JoinEntities(entity.ToArray());
                EmEntityMethod.AddEntity(polyline);
            }
        }

        //找到有相交的Entity，分组并画出那一组的最小包围盒
        [CommandMethod("FindFriends")]
        public void FindFriends()
        {
            if (!UmUserMethod.SelectEntities(out List<Entity> entities)) return;
            var list = EmEntityMethod.GroupEntities(entities, EmEntityMethod.IsOverlapping);
            foreach (var entity in list)
            {
                Extents3d extents = new Extents3d();
                entity.ForEach(x => extents.AddExtents(x.GeometricExtents));
                EmEntityMethod.AddEntity(PmPolylineMethod.CreatePolylineByExtents3d(extents));
            }
        }
        //改参数化
        [CommandMethod("GGG")]
        public void GGG()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId networkId = AssocNetwork.GetInstanceFromObject(db.CurrentSpaceId, false, true, "ACAD_ASSOCNETWORK");
            using (Transaction tran = db.TransactionManager.StartTransaction())
            {
                using (AssocNetwork network = networkId.GetObject(OpenMode.ForWrite) as AssocNetwork)
                {
                    foreach (ObjectId actionId in network.GetActions)
                    {
                        if (actionId.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(AssocVariable))))
                        {
                            AssocVariable var = tran.GetObject(actionId, OpenMode.ForRead, false) as AssocVariable;
                            if (var.Name == "d1")
                            {
                                SetVariableValue(var.ObjectId, null, "500");
                            }
                            if (var.Name == "d2")
                            {
                                SetVariableValue(var.ObjectId, null, "600");
                            }

                        }
                    }
                }
                tran.Commit();
            }
        }
        void SetVariableValue(ObjectId variableId, ResultBuffer value, string expression)
        {

            using (Transaction Tx = variableId.Database.TransactionManager.StartTransaction())
            {
                AssocVariable var = Tx.GetObject(variableId, OpenMode.ForWrite) as AssocVariable;
                if (expression != string.Empty)
                {
                    string errMsg = string.Empty;
                    var.ValidateNameAndExpression(var.Name, expression, ref errMsg);
                    var.SetExpression(expression, "", true, true, ref errMsg, true);
                    ResultBuffer evaluatedExpressionValue = null;
                    var.EvaluateExpression(ref evaluatedExpressionValue);
                    var.Value = evaluatedExpressionValue;
                }
                else var.Value = value;
                Tx.Commit();
            }
        }
        //命令帮助
        [CommandMethod("WCADHelp")]
        public void WCADHelp()
        {
            WCAD.Ed.WriteMessage("还没做！！");
        }

        //扫雷
        [CommandMethod("SaoLei")]
        public void SaoLei()
        {

            if (!BmBlcokMethod.GetBlockTableRecordByName("block", out BlockTableRecord btr)) return;
            List<string> strings = new List<string>() { "1-1" };
            Block[,] blocks = new Block[9, 9];
            int[,] array = new int[9, 9];


            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    BlockReference blockReference = BmBlcokMethod.InsertAttrBlockReference(new Point3d(col, row, 0), btr.ObjectId);
                    Block block = new Block(row + 1, col + 1, blockReference);
                    blocks[row, col] = block;
                }
            }
            bool firstClick = true;
            while (true)
            {

                if (UmUserMethod.GetPoint(out Point3d point))
                {
                    if (point.X > 0 && point.X < 10 && point.Y > 0 && point.Y < 10)
                    {
                        int row = (int)point.Y;
                        int col = (int)point.X;
                        if (firstClick)
                        {

                            Random random = new Random();
                            HashSet<int> bombSet = new HashSet<int>();
                            for (int x = -1; x < 2; x++)
                            {
                                for (int y = -1; y < 2; y++)
                                {
                                    bombSet.Add((row + x) * 10 + (col + y));
                                }
                            }
                            // 将 10 个随机位置设为“雷”，并避免雷重叠
                            while (bombSet.Count < 19)
                            {
                                int x = random.Next(9);
                                int y = random.Next(9);
                                int position = x * 10 + y;
                                if (!bombSet.Contains(position))
                                {
                                    bombSet.Add(position);
                                    array[x, y] = -1;
                                }
                            }

                            // 计算每个位置周围的“雷”的数量
                            for (int x = 0; x < 9; x++)
                            {
                                for (int y = 0; y < 9; y++)
                                {
                                    if (array[x, y] != -1)
                                    {
                                        int count = 0;
                                        for (int dx = -1; dx <= 1; dx++)
                                        {
                                            for (int dy = -1; dy <= 1; dy++)
                                            {
                                                int nx = x + dx;
                                                int ny = y + dy;
                                                if (nx >= 0 && nx < 9 && ny >= 0 && ny < 9 && array[nx, ny] == -1)
                                                {
                                                    count++;
                                                }
                                            }
                                        }
                                        array[x, y] = count;
                                    }
                                }
                            }
                            for (int row1 = 0; row1 < 9; row1++)
                            {
                                for (int col1 = 0; col1 < 9; col1++)
                                {
                                    blocks[row1, col1].Num = array[row1, col1] == -1 ? "雷" : array[row1, col1].ToString();
                                    if (row1 > 0) blocks[row1, col1].Blocks.Add(blocks[row1 - 1, col1]);
                                    if (row1 < 8) blocks[row1, col1].Blocks.Add(blocks[row1 + 1, col1]);
                                    if (col1 > 0) blocks[row1, col1].Blocks.Add(blocks[row1, col1 - 1]);
                                    if (col1 < 8) blocks[row1, col1].Blocks.Add(blocks[row1, col1 + 1]);
                                    if (row1 > 0 && col1 > 0) blocks[row1, col1].Blocks.Add(blocks[row1 - 1, col1 - 1]);
                                    if (row1 > 0 && col1 < 8) blocks[row1, col1].Blocks.Add(blocks[row1 - 1, col1 + 1]);
                                    if (row1 < 8 && col1 > 0) blocks[row1, col1].Blocks.Add(blocks[row1 + 1, col1 - 1]);
                                    if (row1 < 8 && col1 < 8) blocks[row1, col1].Blocks.Add(blocks[row1 + 1, col1 + 1]);
                                }
                            }
                            firstClick = false;
                        }

                        if (blocks[row, col].Click())
                        {
                            DBText dBText = new DBText()
                            {
                                Position = new Point3d(-1, 3, 0),
                                Height = 3,
                                TextString = "输啦！！",
                                ColorIndex = 1
                            };
                            EmEntityMethod.AddEntity(dBText);
                            break;
                        }
                        bool success = true;
                        for (int x = 0; x < 9; x++)
                        {
                            for (int y = 0; y < 9; y++)
                            {
                                if (blocks[x, y].IsHid) success = false;
                            }
                        }
                        if (success)
                        {
                            DBText dBText = new DBText()
                            {
                                Position = new Point3d(-1, 3, 0),
                                Height = 3,
                                TextString = "赢啦！！",
                                ColorIndex = 1
                            };
                            EmEntityMethod.AddEntity(dBText);
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }

        }
        public class Block
        {
            private int Row { get; set; }
            private int Col { get; set; }
            public string Num { get; set; }
            public string Text { get; set; }
            public BlockReference Bl { get; set; }
            public bool IsHid { get; set; }
            public List<Block> Blocks { get; set; }
            public Block(int row, int col, BlockReference bl)
            {
                Blocks = new List<Block>();
                Row = row;
                Col = col;
                Text = row.ToString() + "-" + col.ToString();
                IsHid = true;
                Bl = bl;
            }
            public bool Click()
            {
                if (IsHid)
                {
                    BmBlcokMethod.UpdateAtt(Bl, new Dictionary<string, string> { { "num", Num } });
                    IsHid = false;
                    if (Num == "雷") return true;
                    if (Num == "0")
                    {
                        foreach (var item in Blocks)
                        {
                            item.Click();
                        }
                    }

                }
                else
                {

                    if (int.TryParse(Num, out int n))
                    {
                        List<Block> blocks = Blocks.FindAll(x => x.IsHid || (!x.IsHid && x.Num == "雷")).ToList();
                        if (blocks.Count == n)
                        {
                            foreach (var b in blocks)
                            {
                                BmBlcokMethod.UpdateAtt(b.Bl, new Dictionary<string, string> { { "num", "旗" } });
                                b.IsHid = false;
                            }
                        }
                    }
                }
                return false;
            }

        }

        [CommandMethod("LLL")]
        public void LLL()
        {
            WCAD.Ed.WriteMessage("6666");
        }

        //侧边栏wpf
        [CommandMethod("Clcd")]
        public void Clcd()
        {
            PaletteSet palette = new PaletteSet("菜单");
            PsetArgs psetArgs = new PsetArgs();
            psetArgs.Dic.Add("图库", "Line");
            psetArgs.Dic.Add("自动标注", "Circle");
            psetArgs.Dic.Add("局部放大", "Polyline");
            //psetArgs.Dic.Add("直线", "Line");
            //psetArgs.Dic.Add("圆", "Circle");
            //psetArgs.Dic.Add("多段线", "Polyline");
            //psetArgs.Dic.Add("LLL", "LLL");

            ClcdWpf clcdWpf = new ClcdWpf();
            clcdWpf.DataContext = psetArgs;
            ElementHost host = new ElementHost()
            {
                AutoSize = true,
                Dock = DockStyle.Fill,
                Child = clcdWpf
            };
            palette.Add("111", host);
            palette.Visible = true;
            palette.SetSize(new System.Drawing.Size(120, 500));
            palette.Dock = DockSides.Left;


        }
        public class PsetArgs
        {
            public PsetArgs() { }
            public Dictionary<string, string> Dic { get; set; } = new Dictionary<string, string>();

        }
        //仿源泉线变圆弧
        [CommandMethod("Myxxa")]
        public void Myxxa()
        {
            if (!UmUserMethod.GetEntity(out Entity entity, out Point3d point, "选择多段线/直线/圆弧")) return;
            if (entity is Polyline polyline)
            {
                Polyline pl = polyline.Clone() as Polyline;
                EmEntityMethod.EditEntity(polyline, () =>
                {
                    polyline.Visible = false;
                });
                Jigs.JigPL jigPL = new Jigs.JigPL(pl, point);
                var pr = WCAD.Ed.Drag(jigPL);
                if (pr.Status == PromptStatus.OK)
                {
                    EmEntityMethod.EraseEntity(polyline);
                    EmEntityMethod.AddEntity(jigPL._polyline);
                    EmEntityMethod.EditEntity(jigPL._polyline, () =>
                    {
                        jigPL._polyline.Visible = true;
                    });
                }
                else
                {
                    EmEntityMethod.EditEntity(polyline, () =>
                    {
                        polyline.Visible = true;
                    });
                }
            }
            else if (entity is Line || entity is Arc)
            {
                Curve curve = entity as Curve;
                Jigs.JigLine jigEntity = new Jigs.JigLine(curve.StartPoint, curve.EndPoint);
                EmEntityMethod.EditEntity(curve, () =>
                {
                    curve.Visible = false;
                });
                var pr = WCAD.Ed.Drag(jigEntity);
                if (pr.Status == PromptStatus.OK)
                {
                    EmEntityMethod.EraseEntity(curve);
                    EmEntityMethod.AddEntity(jigEntity._arc);
                }
                else
                {
                    EmEntityMethod.EditEntity(curve, () =>
                    {
                        curve.Visible = true;
                    });
                }
            }

        }
        //孤岛
        [CommandMethod("CCC")]
        public void CCC()
        {
            if (!UmUserMethod.GetEntity(out Polyline polyline, "选择外边框")) return;
            MPolygon mPolygon = new MPolygon();
            mPolygon.AppendLoopFromBoundary(polyline, false, 0);
            if (!UmUserMethod.SelectEntities(out List<Polyline> polylines, "选择孤岛")) return;
            List<MPolygon> mPolygons = new List<MPolygon>();
            foreach (var item in polylines)
            {
                MPolygon mPolygon1 = new MPolygon();
                mPolygon1.AppendLoopFromBoundary(item, false, 0);
                mPolygons.Add(mPolygon1);
            }
            if (!UmUserMethod.GetPoint(out Point3d point, "选择起点")) return;
            if (!UmUserMethod.GetPoint(out Point3d point1, "选择终点")) return;
            HashSet<Point3d> points = new HashSet<Point3d>();
            Queue<Point3d> stack = new Queue<Point3d>();
            stack.Enqueue(point);
            List<DBPoint> points2 = new List<DBPoint>();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Dictionary<Point3d, Point3d> keyValuePairs = new Dictionary<Point3d, Point3d>();
            Point3d p = new Point3d();
            double num = 0.1;
            while (stack.Count > 0)
            {
                p = stack.Dequeue();
                if (points.Contains(p)) continue;
                points.Add(p);


                if (p.DistanceTo(point1) < num)
                {
                    break;
                }
                //Circle circle = new Circle()
                //{
                //    Center=p,
                //    Radius=num/8,
                //};
                //EmEntityMethod.AddEntity(circle);
                //circle.Draw();
                //Line line = new Line(p + new Vector3d(num / 6, num / 6, 0), p + new Vector3d(-num / 6, -num / 6, 0));
                //EmEntityMethod.AddEntity(line);
                //line.Draw();
                //Line line1 = new Line(p + new Vector3d(num / 6, -num / 6, 0), p + new Vector3d(-num / 6, num / 6, 0));
                //EmEntityMethod.AddEntity(line1);
                //line1.Draw();


                Polyline pl = null;
                if (keyValuePairs.ContainsKey(p))
                {
                    Point3d po = keyValuePairs[p];
                    pl = new Polyline();
                    pl.AddVertexAt(0, po.Convert2d(new Plane()), 0, num / 10, num / 10);
                    pl.AddVertexAt(1, new Point2d((p.X + po.X) / 2, (p.Y + po.Y) / 2), 0, num / 5, 0);
                    pl.AddVertexAt(2, p.Convert2d(new Plane()), 0, 0, 0);
                }
                if (mPolygon.IsPointInsideMPolygon(p, 0).Count == 1)
                {
                    if (mPolygons.Any(x => x.IsPointInsideMPolygon(p, 0).Count == 1))
                    {
                        if (pl != null) pl.ColorIndex = 2;
                    }
                    else
                    {
                        if (pl != null) pl.ColorIndex = 1;
                        stack.Enqueue(p + new Vector3d(num, 0, 0));
                        if (!keyValuePairs.ContainsKey(p + new Vector3d(num, 0, 0)))
                        {
                            keyValuePairs.Add(p + new Vector3d(num, 0, 0), p);
                        }
                        stack.Enqueue(p + new Vector3d(-num, 0, 0));
                        if (!keyValuePairs.ContainsKey(p + new Vector3d(-num, 0, 0)))
                        {
                            keyValuePairs.Add(p + new Vector3d(-num, 0, 0), p);
                        }
                        stack.Enqueue(p + new Vector3d(0, num, 0));
                        if (!keyValuePairs.ContainsKey(p + new Vector3d(0, num, 0)))
                        {
                            keyValuePairs.Add(p + new Vector3d(0, num, 0), p);
                        }
                        stack.Enqueue(p + new Vector3d(0, -num, 0));
                        if (!keyValuePairs.ContainsKey(p + new Vector3d(0, -num, 0)))
                        {
                            keyValuePairs.Add(p + new Vector3d(0, -num, 0), p);
                        }
                    }

                }
                else
                {
                    if (pl != null) pl.ColorIndex = 2;
                }
                if (pl != null)
                {
                    //EmEntityMethod.AddEntity(pl);
                    //pl.Draw();
                }
                //var ss = WCAD.Ed.GetDouble("");
                //if (ss.Value == 100) return;
            }
            Polyline pl1 = new Polyline();
            pl1.ColorIndex = 5;
            pl1.AddVertexAt(0, point1.Convert2d(new Plane()), 0, num / 8, num / 8);
            pl1.AddVertexAt(1, p.Convert2d(new Plane()), 0, num / 8, num / 8);
            while (true)
            {
                p = keyValuePairs[p];
                pl1.AddVertexAt(pl1.NumberOfVertices, p.Convert2d(new Plane()), 0, num / 8, num / 8);
                if (p.DistanceTo(point) < 0.1) break;
            }
            while (true)
            {
                bool b = false;
                int ii = 0;
                int jj = 0;
                for (int i = 0; i < pl1.NumberOfVertices - 1; i++)
                {
                    for (int j = pl1.NumberOfVertices - 1; j > i; j--)
                    {
                        Line line = new Line(pl1.GetPoint3dAt(i), pl1.GetPoint3dAt(j));
                        if (polylines.All(x => CmCurveMethod.IntersectWith(x, line, Intersect.OnBothOperands).Count == 0))
                        {
                            ii = i;
                            jj = j;
                            b = true;
                            break;
                        }
                    }
                    if (b) break;
                }
                if (b)
                {
                    for (int i = jj - 1; i > ii; i--)
                    {
                        pl1.RemoveVertexAt(i);
                    }
                    if (jj == ii + 1) break;
                    b = false;
                    continue;

                }
                break;
            }
            EmEntityMethod.AddEntity(pl1);
        }
        [CommandMethod("MMM")]
        public void MMM()
        {
            if (!UmUserMethod.GetEntity(out Polyline polyline, "选择外边框")) return;
            MPolygon mPolygon = new MPolygon();
            mPolygon.AppendLoopFromBoundary(polyline, false, 0);
            if (!UmUserMethod.GetPoint(out Point3d point, "选择起点")) return;
            HashSet<Point3d> points = new HashSet<Point3d>();
            Queue<Point3d> stack = new Queue<Point3d>();
            stack.Enqueue(point);
            List<DBPoint> points2 = new List<DBPoint>();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Dictionary<Point3d, Point3d> keyValuePairs = new Dictionary<Point3d, Point3d>();
            Point3d p = new Point3d();
            double num = (polyline.GeometricExtents.MaxPoint.DistanceTo(polyline.GeometricExtents.MinPoint) / 100);
            while (stack.Count > 0)
            {
                p = stack.Dequeue();
                if (points.Contains(p)) continue;
                points.Add(p);
                Circle circle = new Circle()
                {
                    Center = p,
                    Radius = num / 8,
                };
                EmEntityMethod.AddEntity(circle);
                circle.Draw();
                Line line = new Line(p + new Vector3d(num / 6, num / 6, 0), p + new Vector3d(-num / 6, -num / 6, 0));
                EmEntityMethod.AddEntity(line);
                line.Draw();
                Line line1 = new Line(p + new Vector3d(num / 6, -num / 6, 0), p + new Vector3d(-num / 6, num / 6, 0));
                EmEntityMethod.AddEntity(line1);
                line1.Draw();


                Polyline pl = null;
                if (keyValuePairs.ContainsKey(p))
                {
                    Point3d po = keyValuePairs[p];
                    pl = new Polyline();
                    pl.AddVertexAt(0, po.Convert2d(new Plane()), 0, num / 10, num / 10);
                    pl.AddVertexAt(1, new Point2d((p.X + po.X) / 2, (p.Y + po.Y) / 2), 0, num / 5, 0);
                    pl.AddVertexAt(2, p.Convert2d(new Plane()), 0, 0, 0);
                }
                if (mPolygon.IsPointInsideMPolygon(p, 0).Count == 1)
                {

                    if (pl != null) pl.ColorIndex = 1;
                    stack.Enqueue(p + new Vector3d(num, 0, 0));
                    if (!keyValuePairs.ContainsKey(p + new Vector3d(num, 0, 0)))
                    {
                        keyValuePairs.Add(p + new Vector3d(num, 0, 0), p);
                    }
                    stack.Enqueue(p + new Vector3d(-num, 0, 0));
                    if (!keyValuePairs.ContainsKey(p + new Vector3d(-num, 0, 0)))
                    {
                        keyValuePairs.Add(p + new Vector3d(-num, 0, 0), p);
                    }
                    stack.Enqueue(p + new Vector3d(0, num, 0));
                    if (!keyValuePairs.ContainsKey(p + new Vector3d(0, num, 0)))
                    {
                        keyValuePairs.Add(p + new Vector3d(0, num, 0), p);
                    }
                    stack.Enqueue(p + new Vector3d(0, -num, 0));
                    if (!keyValuePairs.ContainsKey(p + new Vector3d(0, -num, 0)))
                    {
                        keyValuePairs.Add(p + new Vector3d(0, -num, 0), p);
                    }


                }
                else
                {
                    if (pl != null) pl.ColorIndex = 2;
                }
                if (pl != null)
                {
                    EmEntityMethod.AddEntity(pl);
                    pl.Draw();
                }
                WCAD.Ed.UpdateScreen();
            }

        }
        [CommandMethod("MMMM")]
        public void MMMM()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> entities, "选择外边框")) return;
            List<Curve> curves = new List<Curve>();
            //多段线炸开，其余的克隆
            foreach (var item in entities)
            {
                if (item is Polyline)
                {
                    curves.AddRange(PmPolylineMethod.ExplodePolyline(item as Polyline));
                }
                else
                {
                    curves.Add(item.Clone() as Curve);
                }
            }
            Dictionary<Curve, List<Point3d>> keyValuePairs1 = new Dictionary<Curve, List<Point3d>>();
            foreach (var item in curves)
            {
                keyValuePairs1.Add(item, new List<Point3d>());
            }
            for (int i = 0; i < curves.Count; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    List<Point3d> pos = CmCurveMethod.IntersectWith(curves[i], curves[j], Intersect.OnBothOperands);
                    foreach (Point3d item in pos)
                    {
                        keyValuePairs1[curves[i]].Add(item);
                        keyValuePairs1[curves[j]].Add(item);
                    }
                }
            }
            curves.Clear();
            foreach (var item in keyValuePairs1)
            {
                if (item.Value.Count > 0)
                {
                    curves.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
                }
                else
                {
                    curves.Add(item.Key);
                }

            }
            if (!UmUserMethod.GetPoint(out Point3d point, "选择起点")) return;
            HashSet<Point3d> points = new HashSet<Point3d>();
            Queue<Point3d> stack = new Queue<Point3d>();
            stack.Enqueue(point);
            List<DBPoint> points2 = new List<DBPoint>();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Dictionary<Point3d, Point3d> keyValuePairs = new Dictionary<Point3d, Point3d>();
            Point3d p = new Point3d();
            double num = (EmEntityMethod.GetExtents3d(curves).MaxPoint.DistanceTo(EmEntityMethod.GetExtents3d(curves).MinPoint) / 50);
            List<Curve> result = new List<Curve>();
            int n = 0;
            while (stack.Count > 0)
            {
                n++;
                p = stack.Dequeue();
                //if (points.Contains(p)) continue;
                //points.Add(p);
                //Circle circle = new Circle()
                //{
                //    Center = p,
                //    Radius = num / 8,
                //};
                //EmEntityMethod.AddEntity(circle);
                //circle.Draw();
                //Line line = new Line(p + new Vector3d(num / 6, num / 6, 0), p + new Vector3d(-num / 6, -num / 6, 0));
                //EmEntityMethod.AddEntity(line);
                //line.Draw();
                //Line line1 = new Line(p + new Vector3d(num / 6, -num / 6, 0), p + new Vector3d(-num / 6, num / 6, 0));
                //EmEntityMethod.AddEntity(line1);
                //line1.Draw();
                Polyline pl = null;
                if (keyValuePairs.ContainsKey(p))
                {
                    Point3d po = keyValuePairs[p];
                    pl = new Polyline();
                    pl.AddVertexAt(0, po.Convert2d(new Plane()), 0, num / 10, num / 10);
                    pl.AddVertexAt(1, new Point2d((p.X + po.X) / 2, (p.Y + po.Y) / 2), 0, num / 5, 0);
                    pl.AddVertexAt(2, p.Convert2d(new Plane()), 0, 0, 0);
                }
                Point3dCollection point3 = new Point3dCollection();


                if (pl == null || curves.All(x => CmCurveMethod.IntersectWith(pl, x, Intersect.OnBothOperands).Count == 0))
                {

                    if (pl != null) pl.ColorIndex = 1;
                    Point3d p1 = p + new Vector3d(num, 0, 0);
                    Point3d p2 = p + new Vector3d(-num, 0, 0);
                    Point3d p3 = p + new Vector3d(0, num, 0);
                    Point3d p4 = p + new Vector3d(0, -num, 0);
                    if (!points.Contains(p1))
                    {
                        stack.Enqueue(p1);
                        points.Add(p1);
                        keyValuePairs.Add(p1, p);
                    }
                    if (!points.Contains(p2))
                    {
                        stack.Enqueue(p2);
                        points.Add(p2);
                        keyValuePairs.Add(p2, p);
                    }
                    if (!points.Contains(p3))
                    {
                        stack.Enqueue(p3);
                        points.Add(p3);
                        keyValuePairs.Add(p3, p);
                    }
                    if (!points.Contains(p4))
                    {
                        stack.Enqueue(p4);
                        points.Add(p4);
                        keyValuePairs.Add(p4, p);
                    }
                }
                else
                {
                    if (pl != null) pl.ColorIndex = 2;
                    Curve ss = curves.Find(x => CmCurveMethod.IntersectWith(pl, x, Intersect.OnBothOperands).Count == 1);
                    if (!result.Contains(ss))
                    {
                        result.Add(ss);
                    }
                }
                if (pl != null)
                {
                    EmEntityMethod.AddEntity(pl);
                    pl.Draw();
                }
                WCAD.Ed.UpdateScreen();
            }

            //var sss = Region.CreateFromCurves(result.ToDBObjectCollection());
            //List<Entity> ents = new List<Entity>();
            //foreach (Entity item in sss)
            //{
            //    item.ColorIndex = 1;
            //    ents.Add(item);
            //}
            stopwatch.Stop();
            WCAD.Ed.WriteMessage("一共" + n.ToString() + "个," + stopwatch.ElapsedMilliseconds + "毫秒,平均" + (stopwatch.ElapsedMilliseconds / n) + "毫秒一个");

            List<Entity> ents = new List<Entity>();
            foreach (Entity item in result)
            {
                item.ColorIndex = 1;
                ents.Add(item);
            }
            Point3d poo = EmEntityMethod.GetExtents3d(ents).MinPoint;
            Jigs.JigAll jig = new Jigs.JigAll(poo, (pp) =>
            {
                List<Entity> ces = new List<Entity>();
                ents.ForEach(x => ces.Add(x.Clone() as Entity));
                Vector3d vector = pp - poo;
                Matrix3d matrix = Matrix3d.Displacement(vector);
                ces.ForEach(x => x.TransformBy(matrix));
                return ces;
            });
            var sd = WCAD.Ed.Drag(jig);
            if (sd.Status == PromptStatus.OK)
            {
                EmEntityMethod.AddEntities(jig._ents);
            }
        }
        [CommandMethod("MM")]
        public void MM()
        {

            if (!UmUserMethod.SelectEntities(out List<Curve> curves, "选择外边框")) return;
            HashSet<Point3d> intePoints = new HashSet<Point3d>();
            List<Curve3d> curvess = new List<Curve3d>();
            curves.ForEach(x => curvess.Add(x.GetGeCurve()));
            for (int i = 0; i < curves.Count - 1; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    PointOnCurve3d[] ps = curvess[i].GetClosestPointTo(curvess[j], new Tolerance(0.1, 0.1));
                    foreach (PointOnCurve3d item in ps)
                    {
                        Point3d tmp = item.Point;
                        if (curves[i].GetClosestPointTo(tmp, false).DistanceTo(tmp) < 0.1
                            && curves[j].GetClosestPointTo(tmp, false).DistanceTo(tmp) < 0.1)
                        {
                            intePoints.Add(tmp);
                        }

                    }

                }
            }
            if (!UmUserMethod.GetPoint(out Point3d point, "选择起点")) return;
            Queue<Point3d> queue = new Queue<Point3d>();
            HashSet<Point3d> points = new HashSet<Point3d>();
            queue.Enqueue(point);
            points.Add(point);
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Point3d p = new Point3d();
            Extents3d extents = EmEntityMethod.GetExtents3d(curves);
            double num = (extents.MaxPoint.DistanceTo(extents.MinPoint) / 50);
            List<Curve> result = new List<Curve>();
            int n = 0;
            while (queue.Count > 0)
            {
                n++;
                p = queue.Dequeue();

                void AddLine(Point3d p1)
                {
                    if (!points.Contains(p1))
                    {
                        Line line = new Line(p, p1);
                        List<Curve> tmp = curves.FindAll(x => CmCurveMethod.IntersectWith(line, x, Intersect.OnBothOperands).Count > 0);
                        if (tmp.Count == 0)
                        {
                            points.Add(p1);
                            queue.Enqueue(p1);
                            result.Add(line);
                        }
                        else
                        {
                            List<Point3d> tmpPoints = new List<Point3d>();
                            tmp.ForEach(x => tmpPoints.AddRange(CmCurveMethod.IntersectWith(line, x, Intersect.OnBothOperands)));
                            tmpPoints.OrderBy(x => x.DistanceTo(p1));
                            result.Add(new Line(p, tmpPoints[0]));
                        }
                    }
                }
                AddLine(new Point3d(p.X + num, p.Y, 0));
                AddLine(new Point3d(p.X - num, p.Y, 0));
                AddLine(new Point3d(p.X, p.Y + num, 0));
                AddLine(new Point3d(p.X, p.Y - num, 0));
            }
            EmEntityMethod.AddEntities(result);
            //foreach (var item in points)
            //{
            //    Circle circle = new Circle()
            //    {
            //        Center=item,
            //        Radius=0.5,
            //        ColorIndex=1
            //    };
            //    EmEntityMethod.AddEntity(circle);
            //}

            //for (int i = 0; i < curves.Count; i++)
            //{
            //    for (int j = i + 1; j < curves.Count; j++)
            //    {
            //        List<Point3d> pos = CmCurveMethod.GetIntersectPoints(curves[i], curves[j], Intersect.OnBothOperands);
            //        foreach (Point3d item in pos)
            //        {
            //            points.Add(item);
            //        }
            //    }
            //}
            //if (!UmUserMethod.GetPoint(out Point3d point, "选择起点")) return;
            //Queue<Point3d> stack = new Queue<Point3d>();
            //stack.Enqueue(point);
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Start();
            //Point3d p = new Point3d();
            //double num = (EmEntityMethod.GetExtents3d(curves).MaxPoint.DistanceTo(EmEntityMethod.GetExtents3d(curves).MinPoint) / 50);
            //List<Curve> result = new List<Curve>();
            //int n = 0;
            //while (stack.Count > 0)
            //{
            //    n++;
            //    p = stack.Dequeue();
            //    Point3dCollection point3 = new Point3dCollection();
            //    Point3d p1 = new Point3d(p.X + num, p.Y, 0);
            //    Point3d p2 = new Point3d(p.X - num, p.Y, 0);
            //    Point3d p3 = new Point3d(p.X, p.Y + num, 0);
            //    Point3d p4 = new Point3d(p.X, p.Y - num, 0);
            //    LineSegment3d line = new LineSegment3d(p,p1);
            //    //if (pl == null || curves.All(x => CmCurveMethod.GetIntersectPoints(pl, x, Intersect.OnBothOperands).Count == 0))
            //    //{

            //    //    if (pl != null) pl.ColorIndex = 1;
            //    //    Point3d p1 = p + new Vector3d(num, 0, 0);
            //    //    Point3d p2 = p + new Vector3d(-num, 0, 0);
            //    //    Point3d p3 = p + new Vector3d(0, num, 0);
            //    //    Point3d p4 = p + new Vector3d(0, -num, 0);
            //    //    if (!points.Contains(p1))
            //    //    {
            //    //        stack.Enqueue(p1);
            //    //        points.Add(p1);
            //    //        keyValuePairs.Add(p1, p);
            //    //    }
            //    //    if (!points.Contains(p2))
            //    //    {
            //    //        stack.Enqueue(p2);
            //    //        points.Add(p2);
            //    //        keyValuePairs.Add(p2, p);
            //    //    }
            //    //    if (!points.Contains(p3))
            //    //    {
            //    //        stack.Enqueue(p3);
            //    //        points.Add(p3);
            //    //        keyValuePairs.Add(p3, p);
            //    //    }
            //    //    if (!points.Contains(p4))
            //    //    {
            //    //        stack.Enqueue(p4);
            //    //        points.Add(p4);
            //    //        keyValuePairs.Add(p4, p);
            //    //    }
            //    //}
            //    //else
            //    //{
            //    //    if (pl != null) pl.ColorIndex = 2;
            //    //    Curve ss = curves.Find(x => CmCurveMethod.GetIntersectPoints(pl, x, Intersect.OnBothOperands).Count == 1);
            //    //    if (!result.Contains(ss))
            //    //    {
            //    //        result.Add(ss);
            //    //    }
            //    //}
            //    //if (pl != null)
            //    //{
            //    //    EmEntityMethod.AddEntity(pl);
            //    //    pl.Draw();
            //    //}
            //    //WCAD.Ed.UpdateScreen();
            //}

            ////var sss = Region.CreateFromCurves(result.ToDBObjectCollection());
            ////List<Entity> ents = new List<Entity>();
            ////foreach (Entity item in sss)
            ////{
            ////    item.ColorIndex = 1;
            ////    ents.Add(item);
            ////}
            //stopwatch.Stop();
            //WCAD.Ed.WriteMessage("一共" + n.ToString() + "个," + stopwatch.ElapsedMilliseconds + "毫秒,平均" + (stopwatch.ElapsedMilliseconds / n) + "毫秒一个");
            //return;
            //List<Entity> ents = new List<Entity>();
            //foreach (Entity item in result)
            //{
            //    item.ColorIndex = 1;
            //    ents.Add(item);
            //}
            //Point3d poo = EmEntityMethod.GetExtents3d(ents).MinPoint;
            //Jigs.JigAll jig = new Jigs.JigAll(poo, (pp) =>
            //{
            //    List<Entity> ces = new List<Entity>();
            //    ents.ForEach(x => ces.Add(x.Clone() as Entity));
            //    Vector3d vector = pp - poo;
            //    Matrix3d matrix = Matrix3d.Displacement(vector);
            //    ces.ForEach(x => x.TransformBy(matrix));
            //    return ces;
            //});
            //var sd = WCAD.Ed.Drag(jig);
            //if (sd.Status == PromptStatus.OK)
            //{
            //    EmEntityMethod.AddEntities(jig._ents);
            //}
        }
        [CommandMethod("AddSysVarChanged")]
        public void AddSysVarChanged()
        {
            Application.SystemVariableChanged -= sssss;
            Application.SystemVariableChanged += sssss;
        }
        [CommandMethod("RemoveSysVarChanged")]
        public void RemoveSysVarChanged()
        {
            Application.SystemVariableChanged -= sssss;
        }
        [CommandMethod("TTT")]
        public void TTT()
        {
            if (!UmUserMethod.GetEntity(out Entity entity, "选择第一个图形")) return;
            //List<Entity> list = UmUserMethod.SelectAllEntities<Entity>();
            //return;
            //Type type = entity.GetType(); // 获取类型信息
            //PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            //for (int i = 0; i < properties.Count(); i++)
            //{
            //    var v = properties[i].GetValue(entity);
            //    WCAD.Ed.WriteMessage("\n" + properties[i].Name + ": " + v.ToString());
            //}
        }

        private void sssss(object sender, Autodesk.AutoCAD.ApplicationServices.SystemVariableChangedEventArgs e)
        {
            WCAD.Ed.WriteMessage("\n" + e.Name);

        }



        [CommandMethod("ZZZ")]
        public void ZZZ()
        {
            if (UmUserMethod.SelectEntities(out List<Curve> entities, "请选择图形")) return;
            if (!UmUserMethod.GetPoint(out Point3d po, "选择最外面的一个点")) return;
            List<Curve> curves = new List<Curve>();
            //多段线炸开，其余的克隆
            foreach (var item in entities)
            {
                if (item is Polyline)
                {
                    curves.AddRange(PmPolylineMethod.ExplodePolyline(item as Polyline));
                }
                else
                {
                    curves.Add(item.Clone() as Curve);
                }
            }
            Dictionary<Curve, List<Point3d>> keyValuePairs = new Dictionary<Curve, List<Point3d>>();
            foreach (var item in curves)
            {
                keyValuePairs.Add(item, new List<Point3d>());
            }
            for (int i = 0; i < curves.Count; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    List<Point3d> pos = CmCurveMethod.IntersectWith(curves[i], curves[j], Intersect.OnBothOperands);
                    foreach (Point3d item in pos)
                    {
                        keyValuePairs[curves[i]].Add(item);
                        keyValuePairs[curves[j]].Add(item);
                    }
                }
            }
            curves.Clear();
            foreach (var item in keyValuePairs)
            {
                curves.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
            }
            Dictionary<Curve, List<Curve>> pairs = new Dictionary<Curve, List<Curve>>();
            foreach (var item in curves)
            {
                pairs.Add(item, new List<Curve>());
            }
            for (int i = 0; i < curves.Count; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    if (CmCurveMethod.IsTwoCurveConnected(curves[i], curves[j], 0.1))
                    {
                        pairs[curves[i]].Add(curves[j]);
                        pairs[curves[j]].Add(curves[i]);
                    }
                }
            }
            Curve curve = curves.OrderBy(c => c.GetDis(po)).ToArray()[0];
            Point3d closestPoint = curve.GetClosestPointTo(po, false);
            Vector3d vector1 = po.GetVectorTo(closestPoint);
            Vector3d vector2 = curve.GetFirstDerivative(closestPoint);
            if (vector1.X * vector2.Y - vector1.Y * vector2.X > 0)
            {
                curve.ReverseCurve();
            }
            List<Curve> result = new List<Curve> { curve };
            while (true)
            {
                List<Curve> curves1 = pairs[curve];
                if (curves1.Count == 0) break;
                curve = curves1.OrderBy(c => c.GetDis(closestPoint)).ToArray()[0];
                closestPoint = curve.GetClosestPointTo(closestPoint, false);
                vector1 = closestPoint.GetVectorTo(curve.GetClosestPointTo(closestPoint, false));
                vector2 = curve.GetFirstDerivative(closestPoint);
                if (vector1.X * vector2.Y - vector1.Y * vector2.X < 0)
                {
                    curve.ReverseCurve();
                }
                result.Add(curve);
            }
            EmEntityMethod.AddEntity(curve);
        }
        [CommandMethod("Demo")]
        public void Demo()
        {
            if (!UmUserMethod.SelectEntities<Curve>(out List<Curve> curves)) return;
            Curve curve1 = curves[0];
            Curve curve2 = curves[1];
            var sss = CmCurveMethod.IntersectWith(curve1, curve2, Intersect.OnBothOperands);
            List<Entity> entities = new List<Entity>();
            List<Curve> curves1 = new List<Curve>();
            foreach (var item in entities)
            {
                if (item is Curve)
                {
                    curves1.Add(item as Curve);
                }
            }
            curves1 = entities.OfType<Curve>().ToList();
        }


        [CommandMethod("WWWWW")]
        public void WWWWW()
        {
            List<Entity> entities = new List<Entity>();
            string file = @"D:\ikun\";
            for (int i = 1; i <= 59; i++)
            {
                if (entities.Count > 0)
                {
                    EmEntityMethod.EraseEntities(entities);
                    entities = new List<Entity>();
                }
                string path = file + i.ToString() + ".jpg";
                using (var bitmap = new System.Drawing.Bitmap(path))
                {
                    int width = bitmap.Width; // 获取图片宽度
                    int height = bitmap.Height; // 获取图片高度
                    for (int x = 0; x < width; x = x + 10)
                    {
                        for (int y = 0; y < height; y = y + 10)
                        {
                            System.Drawing.Color color = bitmap.GetPixel(x, y);
                            Circle circle = new Circle()
                            {
                                Center = new Point3d(x, -y, 0),
                                LineWeight = LineWeight.LineWeight060,
                                Color = Autodesk.AutoCAD.Colors.Color.FromRgb(color.R, color.G, color.B)
                            };
                            entities.Add(circle);
                        }
                    }
                }
                EmEntityMethod.AddEntities(entities);
                double d;
                UmUserMethod.GetDouble(out d);
            }
        }

        /// <summary>
        /// 多段线新增节点或者删除节点
        /// </summary>
        [CommandMethod("Myxxv")]
        public void Myxxv()
        {
            if (!UmUserMethod.GetEntity(out Polyline polyline, "请选择一个多段线")) return;
            WCAD.Ed.SetImpliedSelection(new ObjectId[] { polyline.ObjectId });
            WCAD.Ed.Regen();
            while (true)
            {
                if (UmUserMethod.GetPoint(out Point3d point, "请选择点"))
                {
                    Point3d po = polyline.GetClosestPointTo(point, false);
                    bool onLine = false;
                    if (po.DistanceTo(point) < 0.00001)
                    {
                        onLine = true;
                    }
                    double p = polyline.GetParameterAtPoint(po);
                    using (Transaction trans = WCAD.Trans)
                    {
                        polyline.ObjectId.GetObject(OpenMode.ForWrite);
                        if (Math.Floor(p) == p)
                        {
                            int num = (int)p;
                            if (onLine)
                            {
                                polyline.RemoveVertexAt(num);
                            }
                            else
                            {
                                polyline.AddVertexAt(num == 0 ? 0 : num + 1, point.Convert2d(new Plane()), 0, 0, 0);
                            }
                        }
                        else
                        {
                            polyline.AddVertexAt((int)Math.Ceiling(p), point.Convert2d(new Plane()), 0, 0, 0);
                        }
                        trans.Commit();
                    }
                }
                else
                {
                    break;
                }
            }
        }

        /// <summary>
        /// 填充
        /// </summary>
        [CommandMethod("SSS")]
        public static void SSS()
        {

            //if (!UmUserMethod.GetEntity("", out Circle circle)) return;
            Circle circle = new Circle()
            {
                Center = Point3d.Origin
            };
            EmEntityMethod.AddEntity(circle);
            //using (Transaction tran = WCAD.Trans)
            //{
            //    var ddd = block.AttributeCollection;
            //    block.ObjectId.GetObject(OpenMode.ForWrite);
            //    if (block.IsDynamicBlock)
            //    {
            //        foreach (DynamicBlockReferenceProperty item in block.DynamicBlockReferencePropertyCollection)
            //        {
            //            if (item.PropertyName=="块表1")
            //            {
            //                var sssss= item.Value;
            //                var dd = sssss.GetType();
            //                var sss = item.GetAllowedValues();
            //               // item.Value =Convert.ToInt16(10);
            //            }
            //            var ss = item.GetAllowedValues();
            //            //item.Value = "隔离柜";
            //        }
            //    }
            //    tran.Commit();
            //}
            string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string file = @"E:\地毯.pat";
            string tmp = @"C:\Program Files\Autodesk\AutoCAD 2022\Support\地毯.pat";
            if (File.Exists(tmp)) File.Delete(tmp);
            File.Copy(file, tmp);



            //string file = @"E:\FA木纹深SC1000.pat";

            Hatch hatch = new Hatch();
            hatch.PatternScale = 20;
            hatch.ColorIndex = 256;
            hatch.SetHatchPattern(HatchPatternType.CustomDefined, "地毯");
            //if (!UmUserMethod.GetEntity("", out Polyline polyline)) return;
            //hatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { polyline.ObjectId });
            //List<Curve> lines = UmUserMethod.SelectEntities<Curve>("");
            //ObjectIdCollection objectIdCollection = new ObjectIdCollection();
            //lines.ForEach(l => objectIdCollection.Add(l.ObjectId));
            //hatch.AppendLoop(HatchLoopTypes.Default, objectIdCollection);
            //hatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { lines[0].ObjectId });
            //hatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { lines[1].ObjectId });
            //hatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { lines[2].ObjectId });
            //hatch.Origin = new Point2d(4213, 1291);
            EmEntityMethod.AddEntity(hatch);
        }

        /// <summary>
        /// 缩放多段线中一段
        /// </summary>
        [CommandMethod("TTTT")]
        public static void TTTT()
        {
            if (!UmUserMethod.GetEntity(out Polyline polyline)) return;
            if (!UmUserMethod.GetInt(out int num, "第几节点")) return;
            if (!UmUserMethod.GetDouble(out double dis, "长度")) return;

            EmEntityMethod.EditEntity(polyline, () =>
            {
                PmPolylineMethod.ExtendPolyline(polyline, num, dis);
            });

        }
        /// <summary>
        /// 鼠标边图片
        /// </summary>
        [CommandMethod("OOO")]
        public static void OOO()
        {
            WCAD.CreateFormatBrushCursor();
        }
        /// <summary>
        /// 关鼠标边图片
        /// </summary>
        [CommandMethod("PPP")]
        public static void PPP()
        {
            WCAD.DeleteFormatBrushCursor();
        }
        /// <summary>
        /// 点文字写excel
        /// </summary>
        [CommandMethod("TextToExcel")]
        public static void TextToExcel()
        {
            ExcelMethod.OpenExcel(@"C:\Users\Administrator\Desktop\example.xls");
            WCAD.FocusDoc();
            while (UmUserMethod.GetEntity(out DBText dBText, "选择文字"))
            {
                string text = dBText.TextString;
                for (int i = 1; i < 100; i++)
                {
                    if (ExcelMethod.GetCell(i, 1) == null)
                    {
                        ExcelMethod.SetCell(i, 1, text);
                        break;
                    }
                }
            }
        }
        [CommandMethod("SaveWblock")]
        public static void SaveWblock()
        {
            if (!UmUserMethod.SelectEntities(out List<Entity> ents)) return;
            if (!UmUserMethod.GetPoint(out Point3d point)) return;
            Database database = BmBlcokMethod.Wblock(ents, point);
            database.SaveAs(@"C:\Users\Administrator\Desktop\example.dwg", DwgVersion.Current);
        }
        /// <summary>
        /// Mline内轮廓
        /// </summary>
        [CommandMethod("NLK")]
        public static void NLK()
        {
            if (!UmUserMethod.SelectEntities(out List<Mline> mlines, "请选择图形")) return;

            List<Curve> curves = new List<Curve>();
            foreach (var item in mlines)
            {
                curves.AddRange(CmCurveMethod.ExplodeMline(item));
            }
            Dictionary<Curve, List<Point3d>> keyValuePairs = new Dictionary<Curve, List<Point3d>>();
            foreach (var item in curves)
            {
                keyValuePairs.Add(item, new List<Point3d>());
            }
            for (int i = 0; i < curves.Count; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    List<Point3d> pos = CmCurveMethod.IntersectWith(curves[i], curves[j], Intersect.OnBothOperands);
                    foreach (Point3d item in pos)
                    {
                        keyValuePairs[curves[i]].Add(item);
                        keyValuePairs[curves[j]].Add(item);
                    }
                }
            }
            curves.Clear();
            foreach (var item in keyValuePairs)
            {
                curves.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
            }
            List<Curve> curves1 = new List<Curve>();
            foreach (var item in curves)
            {
                if (!mlines.Any(x => x.GetClosestPointTo(item.StartPoint, false, true).DistanceTo(item.StartPoint) < 0.01 && x.GetClosestPointTo(item.EndPoint, false, true).DistanceTo(item.EndPoint) < 0.01 && x.GetClosestPointTo((item.GetGeCurve() as LineSegment3d).MidPoint, false, true).DistanceTo((item.GetGeCurve() as LineSegment3d).MidPoint) > 0.01))
                {
                    curves1.Add(item);
                }
            }
            DBObjectCollection dbs = new DBObjectCollection();
            curves1.ForEach(x => dbs.Add(x));
            var ss = Region.CreateFromCurves(dbs);
            List<Region> regions = new List<Region>();
            foreach (Region region in ss)
            {
                region.ColorIndex = 1;
                regions.Add(region);
            }
            EmEntityMethod.AddEntities(regions);
        }
        [CommandMethod("Test1")]
        public static void Test1()
        {
            if (!UmUserMethod.GetEntity(out BlockReference bl1, "第一个块")) return;
            //if (!UmUserMethod.GetEntity(out BlockReference bl2, "第二个块")) return;


            if (!UmUserMethod.GetEntity(out Polyline polyline, "选多段线")) return;
            List<Entity> entities = new List<Entity>();
            for (int i = 1; i < polyline.NumberOfVertices - 1; i++)
            {
                BlockReference block = BmBlcokMethod.InsertAttrBlockReference(polyline.GetPoint3dAt(i), bl1.BlockTableRecord);
                //entities.Add(block);
            }
            BlockReference block1 = BmBlcokMethod.InsertAttrBlockReference(polyline.StartPoint, bl1.BlockTableRecord);
            BlockReference block2 = BmBlcokMethod.InsertAttrBlockReference(polyline.EndPoint, bl1.BlockTableRecord);
            //entities.Add(block1);
            //entities.Add(block2);
            //EmEntityMethod.AddEntities(entities);
        }

        [CommandMethod("CreatRec")]
        public static void CreatRec()
        {
            if (!UmUserMethod.GetPoint(out Point3d point1, "选第一个点")) return;
            Jigs.JigRec jig = new Jigs.JigRec(point1);
            var ss = WCAD.Ed.Drag(jig);
            if (ss.Status == PromptStatus.OK)
            {
                Jigs.JigRec jig1 = new Jigs.JigRec(jig._line);
                ss = WCAD.Ed.Drag(jig1);
                if (ss.Status == PromptStatus.OK)
                {
                    EmEntityMethod.AddEntity(jig1._pl);
                }
            }
        }
        [CommandMethod("Test2")]
        public static void Test2()
        {

        }
        [CommandMethod("LJ")]
        public static void LJ()
        {
            Application.DocumentManager.DocumentLockModeChanged -= DocumentManager_DocumentLockModeChanged;
            Application.DocumentManager.DocumentLockModeChanged += DocumentManager_DocumentLockModeChanged;
        }
        [CommandMethod("NOLJ")]
        public static void NOLJ()
        {
            Application.DocumentManager.DocumentLockModeChanged -= DocumentManager_DocumentLockModeChanged;
        }
        private static void DocumentManager_DocumentLockModeChanged(object sender, DocumentLockModeChangedEventArgs e)
        {
            string ss = e.GlobalCommandName;
        }

        [CommandMethod("ChatPPP")]
        public void ChatPPP()
        {
            Polyline polyline;
            if (!UmUserMethod.GetString(out string str, "请输入你的要求")) return;
            if (str.Contains("不对"))
            {
                EmEntityMethod.EraseEntities(UmUserMethod.SelectAllEntities<Entity>());
                polyline = new Polyline();
                polyline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
                polyline.AddVertexAt(1, new Point2d(700, 0), 0, 0, 0);
                polyline.AddVertexAt(2, new Point2d(700, 600), 0, 0, 0);
                polyline.AddVertexAt(3, new Point2d(0, 600), 0, 0, 0);
                polyline.Closed = true;
                EmEntityMethod.AddEntity(polyline);
                double rotation = 0;
                Point3d line1Point = new Point3d(0, 600, 0);
                Point3d line2Point = new Point3d(700, 600, 0);
                Point3d dimensionLinePoint = new Point3d(350, 700, 0);
                string dimensionText = "";
                Document doc = Application.DocumentManager.MdiActiveDocument;
                ObjectId dimensionStyle = doc.Database.DimStyleTableId;
                RotatedDimension rotatedDimension = new RotatedDimension(rotation, line1Point, line2Point, dimensionLinePoint, dimensionText, dimensionStyle);
                EmEntityMethod.AddEntity(rotatedDimension);
                double rotation1 = -Math.PI / 2;
                Point3d line1Point1 = new Point3d(700, 600, 0);
                Point3d line2Point1 = new Point3d(700, 0, 0);
                Point3d dimensionLinePoint1 = new Point3d(800, 300, 0);
                string dimensionText1 = "";
                RotatedDimension rotatedDimension1 = new RotatedDimension(rotation1, line1Point1, line2Point1, dimensionLinePoint1, dimensionText1, dimensionStyle);
                EmEntityMethod.AddEntity(rotatedDimension1);
            }
            else if (str.Contains("矩形"))
            {
                polyline = new Polyline();
                polyline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
                polyline.AddVertexAt(1, new Point2d(600, 0), 0, 0, 0);
                polyline.AddVertexAt(2, new Point2d(600, 500), 0, 0, 0);
                polyline.AddVertexAt(3, new Point2d(0, 500), 0, 0, 0);
                polyline.Closed = true;
                EmEntityMethod.AddEntity(polyline);

            }
            else
            {
                double rotation = 0;
                Point3d line1Point = new Point3d(0, 500, 0);
                Point3d line2Point = new Point3d(600, 500, 0);
                Point3d dimensionLinePoint = new Point3d(300, 600, 0);
                string dimensionText = "";
                Document doc = Application.DocumentManager.MdiActiveDocument;
                ObjectId dimensionStyle = doc.Database.DimStyleTableId;
                RotatedDimension rotatedDimension = new RotatedDimension(rotation, line1Point, line2Point, dimensionLinePoint, dimensionText, dimensionStyle);
                EmEntityMethod.AddEntity(rotatedDimension);
                double rotation1 = -Math.PI / 2;
                Point3d line1Point1 = new Point3d(600, 500, 0);
                Point3d line2Point1 = new Point3d(600, 0, 0);
                Point3d dimensionLinePoint1 = new Point3d(700, 250, 0);
                string dimensionText1 = "";
                RotatedDimension rotatedDimension1 = new RotatedDimension(rotation1, line1Point1, line2Point1, dimensionLinePoint1, dimensionText1, dimensionStyle);
                EmEntityMethod.AddEntity(rotatedDimension1);
            }
        }
        [CommandMethod("ChangeColor")]
        public void ChangeColor()
        {

            if (!UmUserMethod.GetEntity(out Entity entity)) return;
            EmEntityMethod.EditEntity(entity, () =>
            {
                entity.Visible = false;
            });
            int n = entity.ColorIndex;
            //return;
            double d = entity.GeometricExtents.MinPoint.DistanceTo(entity.GeometricExtents.MaxPoint);
            Jigs.JigEnts jig = new Jigs.JigEnts(entity.GeometricExtents.MinPoint + entity.GeometricExtents.MinPoint.GetVectorTo(entity.GeometricExtents.MaxPoint) / 2, d / 2, entity);
            var sss = WCAD.Ed.Drag(jig);
            if (sss.Status == PromptStatus.OK)
            {
                EmEntityMethod.EditEntity(entity, () =>
                {
                    entity.Color = jig._ent.Color;
                });
            }
            EmEntityMethod.EditEntity(entity, () =>
            {
                entity.Visible = true;
            });
        }

        [CommandMethod("Rainbow")]
        public void Rainbow()
        {
            if (!UmUserMethod.SelectEntities(out List<DBPoint> points)) return;
            Extents3d extents = EmEntityMethod.GetExtents3d(points);
            EmEntityMethod.EditEntities(points, () =>
            {
                foreach (DBPoint item in points)
                {
                    item.Color = RgbColorMethod.RainbowAll(item.Position.X - extents.MinPoint.X, extents.MaxPoint.X - extents.MinPoint.X);
                }
            });
        }
        [CommandMethod("ZZZZ")]
        public void ZZZZ()
        {
            if (!UmUserMethod.GetEntity(out Polyline polyline, "选择多段线")) return;
            if (!UmUserMethod.GetDouble(out double d, "输入小数")) return;
            List<int> angles = new List<int>();
            angles.Add(200);
            for (int i = 1; i < polyline.NumberOfVertices - 1; i++)
            {
                Vector3d vector1 = polyline.GetPoint3dAt(i - 1) - polyline.GetPoint3dAt(i);
                Vector3d vector2 = polyline.GetPoint3dAt(i + 1) - polyline.GetPoint3dAt(i);
                double ddd = vector1.GetAngleTo(vector2, Vector3d.ZAxis) / Math.PI * 180;
                angles.Add((int)Math.Round(ddd));
            }
            angles.Add(200);
            double GetD(int i)
            {
                if (i <= 40 || (i > 135 && i < 180)) return d / Math.Tan(i * Math.PI / 180 / 2);
                if (i > 40 && i <= 135) return d / Math.Tan(i * Math.PI / 180 / 2) - d;
                return 0;
            }
            EmEntityMethod.EditEntity(polyline, () =>
            {
                for (int i = 1; i < polyline.NumberOfVertices; i++)
                {
                    double dis = GetD(angles[i - 1]) + GetD(angles[i]);
                    if (dis == 0) continue;
                    PmPolylineMethod.ExtendPolyline(polyline, i, dis);
                }
            });

        }

        [CommandMethod("TT")]
        public void TT()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curs)) return;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < curs.Count - 1; i++)
            {
                for (int j = i + 1; j < curs.Count; j++)
                {
                    if (curs[i].GeometricExtents.ExtensHit(curs[j].GeometricExtents))
                    {
                        CmCurveMethod.IntersectWith(curs[i], curs[j], Intersect.OnBothOperands);

                    }
                }
            }
            stopwatch.Stop();
            WCAD.Ed.WriteMessage(curs.Count.ToString() + "条线求交点耗时:" + stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
            //Curve curve1 = curs[0];
            //Curve curve2 = curs[1];
            //Extents3d extents1 = curve1.GeometricExtents;
            //Extents3d extents2  =curve2.GeometricExtents;
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Start();
            //int m = 100000;
            //for (int i = 0; i < m; i++)
            //{
            //    CmCurveMethod.GetIntersectPoints(curve1, curve2, Intersect.OnBothOperands);
            //}
            //stopwatch.Stop();
            ////WCAD.Ed.WriteMessage(m.ToString()+"次，求交点耗时:"+stopwatch.ElapsedMilliseconds.ToString()+"毫秒");
            //stopwatch.Restart();
            //for (int i = 0; i < m; i++)
            //{
            //    //if (extents1.ExtensHit(extents2))
            //    //{

            //    //}
            //    Point3d p1 = curve1.StartPoint;
            //    Point3d p2 = curve1.EndPoint;

            //    double d = Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
            //}
            //stopwatch.Stop();
            //WCAD.Ed.WriteMessage("100000次数学求两点距离耗时:" + stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
            //stopwatch.Restart();
            //for (int i = 0; i < m; i++)
            //{
            //    double d = curve1.StartPoint.DistanceTo(curve1.EndPoint);
            //}
            //stopwatch.Stop();
            //WCAD.Ed.WriteMessage("，DistanceTo求两点距离耗时:" + stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
        }

        [CommandMethod("ZZ")]
        public void ZZ()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curs, "请选择线")) return;
            if (!UmUserMethod.GetPoint(out Point3d point, "请选择一点")) return;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Extents3d extents = EmEntityMethod.GetExtents3d(curs);
            double minx = extents.MinPoint.X;
            double miny = extents.MinPoint.Y;
            double maxx = extents.MaxPoint.X;
            double maxy = extents.MaxPoint.Y;
            double num = extents.MinPoint.DistanceTo(extents.MaxPoint);
            if (!UmUserMethod.GetInt(out int mm, "请输入精度")) return;
            num /= mm;
            Point3d minPo = new Point3d(point.X - Math.Ceiling((point.X - minx) / num) * num, point.Y - Math.Ceiling((point.Y - miny) / num) * num, 0);
            Point3d maxPo = new Point3d(point.X + Math.Ceiling((maxx - point.X) / num) * num, point.Y + Math.Ceiling((maxy - point.Y) / num) * num, 0);
            //List<Line> lines = new List<Line>();
            //for (double i = minPo.X; i <= maxPo.X + num / 100; i += num)
            //{
            //    Line line = new Line(new Point3d(i, minPo.Y, 0), new Point3d(i, maxPo.Y, 0));
            //    line.ColorIndex = 1;
            //    lines.Add(line);
            //}
            //for (double i = minPo.Y; i <= maxPo.Y + num / 100; i += num)
            //{
            //    Line line = new Line(new Point3d(minPo.X, i, 0), new Point3d(maxPo.X, i, 0));
            //    line.ColorIndex = 1;
            //    lines.Add(line);
            //}
            //EmEntityMethod.AddEntities(lines);
            int row = Convert.ToInt32((maxPo.Y - minPo.Y + num / 100) / num);
            int col = Convert.ToInt32((maxPo.X - minPo.X + num / 100) / num);
            List<Curve>[,] curves = new List<Curve>[row, col];
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    curves[i, j] = new List<Curve>(); // 初始化每个元素为 new List<Curve>()
                }
            }
            foreach (var item in curs)
            {
                Extents3d ext = item.GeometricExtents;
                int xx = (int)((ext.MinPoint.X - minPo.X) / num);
                int yy = (int)((ext.MinPoint.Y - minPo.Y) / num);
                int xxx = (int)((ext.MaxPoint.X - minPo.X) / num);
                if (xxx == col) xxx--;
                int yyy = (int)((ext.MaxPoint.Y - minPo.Y) / num);
                if (yyy == row) yyy--;
                for (int i = yy; i <= yyy; i++)
                {
                    for (int j = xx; j <= xxx; j++)
                    {
                        curves[i, j].Add(item);
                    }
                }
            }
            HashSet<Point3d> points = new HashSet<Point3d>();
            Queue<Point3d> queue = new Queue<Point3d>();
            queue.Enqueue(point);
            points.Add(point);
            List<Line> ls = new List<Line>();
            List<Curve> result = new List<Curve>();
            List<Point2d> pos = new List<Point2d>();
            while (queue.Count > 0)
            {
                Point3d p = queue.Dequeue();
                int r = (int)Math.Round((p.Y - miny) / num);
                if (r == row - 1) r--;
                if (r == 0) r++;
                int c = (int)Math.Round((p.X - minx) / num);
                if (c == col - 1) c--;
                if (c == 0) c++;
                List<Curve> tmpCurves = new List<Curve>();
                tmpCurves.AddRange(curves[r, c]);
                tmpCurves.AddRange(curves[r - 1, c]);
                tmpCurves.AddRange(curves[r + 1, c]);
                tmpCurves.AddRange(curves[r, c - 1]);
                tmpCurves.AddRange(curves[r, c + 1]);
                tmpCurves.AddRange(curves[r - 1, c - 1]);
                tmpCurves.AddRange(curves[r - 1, c + 1]);
                tmpCurves.AddRange(curves[r + 1, c - 1]);
                tmpCurves.AddRange(curves[r + 1, c + 1]);
                tmpCurves = tmpCurves.Distinct().ToList();


                void AddLine(Point3d po)
                {
                    if (!points.Contains(po))
                    {
                        Line line = new Line(p, po);
                        line.ColorIndex = 2;
                        if (tmpCurves.All(x => CmCurveMethod.IntersectWith(line, x, Intersect.OnBothOperands).Count == 0))
                        {
                            points.Add(po);
                            queue.Enqueue(po);
                        }
                        else
                        {
                            Point3d point1 = minPo;
                            Curve cu = null;
                            foreach (var item in tmpCurves)
                            {
                                List<Point3d> ps = CmCurveMethod.IntersectWith(item, line, Intersect.OnBothOperands);
                                foreach (var item1 in ps)
                                {
                                    if (p.DistanceTo(item1) < p.DistanceTo(point1))
                                    {
                                        point1 = item1;
                                        cu = item;
                                    }
                                }
                            }
                            //result.Add(cu);
                            if (cu is Spline)
                            {
                                pos.Add(new Point2d(point1.X, point1.Y));
                            }

                            line.EndPoint = point1;
                        }
                        //ls.Add(line);
                        //EmEntityMethod.AddEntity(line);
                        //line.Draw();
                        //WCAD.Ed.GetDouble("");
                    }

                }
                if (p.X > minx) AddLine(new Point3d(p.X - num, p.Y, 0));
                if (p.Y < maxy) AddLine(new Point3d(p.X, p.Y + num, 0));
                if (p.X < maxx) AddLine(new Point3d(p.X + num, p.Y, 0));
                if (p.Y > miny) AddLine(new Point3d(p.X, p.Y - num, 0));
            }
            //result.Distinct();
            //result = result.FindAll(x => x is Spline);
            //EmEntityMethod.EditEntities(result, () =>
            //{
            //    result.ForEach(x => x.Highlight());
            //});
            //EmEntityMethod.AddEntities(ls);
            List<Point2d> ds = new List<Point2d>();
            foreach (var item in pos)
            {
                if (ds.All(x => x.GetDistanceTo(item) > 0.01))
                {
                    ds.Add(item);
                }
            }
            pos = ds;
            //stopwatch.Stop();
            //WCAD.Ed.WriteMessage(mm.ToString() + "精度,用时" + stopwatch.ElapsedMilliseconds + "毫秒");
            //stopwatch.Restart();
            Polyline pl = new Polyline();
            Point2d ppp = pos[0];
            pl.AddVertexAt(0, pos[0], 0, 0, 0);
            pos.RemoveAt(0);
            int n = 0;
            while (pos.Count > 0)
            {

                pos = pos.OrderBy(x => x.GetDistanceTo(ppp)).ToList();
                ppp = pos[0];
                pl.AddVertexAt(0, ppp, 0, 0, 0);

                pos.RemoveAt(0);
                n++;
                //if (n > 10) break;
            }
            pl.Closed = true;
            pl.ColorIndex = 1;
            EmEntityMethod.AddEntity(pl);
            stopwatch.Stop();
            WCAD.Ed.WriteMessage(mm.ToString() + "精度,用时" + stopwatch.ElapsedMilliseconds + "毫秒");
        }
        [CommandMethod("Zhuanhua")]
        public void Zhuanhua()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves, "选择图形")) return;
            if (!UmUserMethod.GetEntity(out Curve curve1, out Point3d p1, "选第一个曲线")) return;
            if (!UmUserMethod.GetEntity(out Curve curve2, out Point3d p2, "选第二个曲线")) return;
            Curve c1 = curve1.Clone() as Curve;
            Curve c2 = curve2.Clone() as Curve;
            double lenC1 = c1.GetDistAtPoint(c1.EndPoint);
            double lenC2 = c2.GetDistAtPoint(c2.EndPoint);
            if (c1.StartPoint.DistanceTo(p1) > c1.EndPoint.DistanceTo(p1)) c1.ReverseCurve();
            if (c2.StartPoint.DistanceTo(p2) > c2.EndPoint.DistanceTo(p2)) c2.ReverseCurve();
            Extents3d extents = EmEntityMethod.GetExtents3d(curves);
            double width = extents.MaxPoint.X - extents.MinPoint.X;
            double height = extents.MaxPoint.Y - extents.MinPoint.Y;
            double minx = extents.MinPoint.X;
            double miny = extents.MinPoint.Y;
            List<Polyline> polylines = new List<Polyline>();
            int m = 200;
            foreach (var item in curves)
            {
                var cc = item.GetGeCurve();
                double dis = item.GetDistanceAtParameter(item.EndParam);
                dis /= m;
                Polyline polyline = new Polyline();
                polyline.Color = item.Color;
                for (int i = 0; i < m; i++)
                {
                    polyline.AddVertexAt(i, item.GetPointAtDist(i * dis).Convert2d(new Plane()), 0, 0, 0);
                }
                polyline.AddVertexAt(m, item.EndPoint.Convert2d(new Plane()), 0, 0, 0);
                polylines.Add(polyline);
            }
            foreach (var item in polylines)
            {
                for (int i = 0; i < item.NumberOfVertices; i++)
                {
                    Point2d point = item.GetPoint2dAt(i);
                    double xx = (point.X - minx) / width;
                    double yy = (point.Y - miny) / height;
                    Point3d point1 = c1.GetPointAtDist(lenC1 * xx);
                    Point3d point2 = c2.GetPointAtDist(lenC2 * xx);
                    Vector3d vector = point2 - point1;
                    vector *= yy;
                    Point3d point3D = point1 + vector;
                    item.SetPointAt(i, point3D.Convert2d(new Plane()));
                }
            }
            EmEntityMethod.AddEntities(polylines);
        }
        [CommandMethod("Zhuanhua1")]
        public void Zhuanhua1()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves, "选择图形")) return;

            if (!UmUserMethod.GetPoint(out Point3d pp)) return;
            Extents3d extents = EmEntityMethod.GetExtents3d(curves);
            double width = extents.MaxPoint.X - extents.MinPoint.X;
            double height = extents.MaxPoint.Y - extents.MinPoint.Y;
            double minx = extents.MinPoint.X;
            double miny = extents.MinPoint.Y;
            Line lin1 = new Line(extents.MinPoint, pp);
            Line lin2 = new Line(extents.MinPoint + new Vector3d(width, 0, 0), pp);
            Line lin3 = new Line(extents.MinPoint + new Vector3d(0, height, 0), pp);
            Line lin4 = new Line(extents.MaxPoint, pp);
            int n = 20;
            EmEntityMethod.EditEntities(curves, () => curves.ForEach(x => x.Visible = false));
            List<Polyline> polylines = new List<Polyline>();
            int m = 200;
            foreach (var item in curves)
            {
                var cc = item.GetGeCurve();
                double dis = item.GetDistanceAtParameter(item.EndParam);
                dis /= m;
                Polyline polyline = new Polyline();
                polyline.Color = item.Color;
                for (int i = 0; i < m; i++)
                {
                    polyline.AddVertexAt(i, item.GetPointAtDist(i * dis).Convert2d(new Plane()), 0, 0, 0);
                }
                polyline.AddVertexAt(m, item.EndPoint.Convert2d(new Plane()), 0, 0, 0);
                polylines.Add(polyline);

            }
            List<Polyline> tmp = new List<Polyline>();

            for (int j = 0; j < n; j++)
            {
                if (tmp.Count > 0) EmEntityMethod.EraseEntities(tmp);
                tmp.Clear();
                foreach (var item in polylines)
                {
                    tmp.Add(item.Clone() as Polyline);
                }
                double d = (double)j / n;
                //Curve c1 = new Line(lin1.GetPointAtParameter(lin1.Length*d), lin2.GetPointAtParameter(lin2.Length * d));
                Curve c1 = new Line(pp, pp + new Vector3d(1, 0, 0));
                Curve c2 = new Line(lin3.GetPointAtParameter(lin3.Length * d), lin4.GetPointAtParameter(lin4.Length * d));

                double lenC1 = c1.GetDistAtPoint(c1.EndPoint);
                double lenC2 = c2.GetDistAtPoint(c2.EndPoint);



                foreach (var item in tmp)
                {
                    for (int i = 0; i < item.NumberOfVertices; i++)
                    {
                        Point2d point = item.GetPoint2dAt(i);
                        double xx = (point.X - minx) / width;
                        double yy = (point.Y - miny) / height;
                        Point3d point1 = c1.GetPointAtDist(lenC1 * xx);
                        Point3d point2 = c2.GetPointAtDist(lenC2 * xx);
                        Vector3d vector = point2 - point1;
                        vector *= yy;
                        Point3d point3D = point1 + vector;
                        item.SetPointAt(i, point3D.Convert2d(new Plane()));
                    }
                }
                EmEntityMethod.AddEntities(tmp);
                //WCAD.Ed.GetDouble("");
                WCAD.Ed.UpdateScreen();
            }
            if (tmp.Count > 0) EmEntityMethod.EraseEntities(tmp);
        }
        [CommandMethod("DrawTree")]
        public void DrawTree()
        {
            if (!UmUserMethod.GetPoint(out Point3d point, "选第一个点")) return;
            Jigs.JigAll jig = new Jigs.JigAll(point, (p) =>
            {
                List<Entity> entities = new List<Entity>();
                Line line = new Line(point, p);

                entities.Add(line);
                return entities;
            });
            if (WCAD.Ed.Drag(jig).Status == PromptStatus.OK)
            {
                EmEntityMethod.AddEntities(jig._ents);
                Tree1(jig._ents[0] as Line, 200);
            }
        }
        private void Tree(Line line, int n)
        {
            n--;
            Line line1 = new Line(line.EndPoint, line.EndPoint + line.Delta.RotateBy(0, Vector3d.ZAxis) * 0.8);
            EmEntityMethod.AddEntity(line1);
            WCAD.Ed.UpdateScreen();
            Line line2 = new Line(line.EndPoint, line.EndPoint + line.Delta.RotateBy(-Math.PI / 3, Vector3d.ZAxis) * 0.6);
            EmEntityMethod.AddEntity(line2);
            WCAD.Ed.UpdateScreen();
            Line line3 = new Line(line.EndPoint, line.EndPoint + line.Delta.RotateBy(Math.PI / 3, Vector3d.ZAxis) * 0.6);
            WCAD.Ed.UpdateScreen();
            EmEntityMethod.AddEntity(line3);
            if (n > 0)
            {
                Tree(line2, n);
                Tree(line3, n);
                Tree(line1, n);
            }
        }
        private void Tree1(Line line, int n)
        {
            n--;
            Line line1 = new Line(line.EndPoint, line.EndPoint + line.Delta.RotateBy(Math.PI / 3, Vector3d.ZAxis) * 0.8);
            EmEntityMethod.AddEntity(line1);
            WCAD.Ed.UpdateScreen();

            if (n > 0)
            {
                Tree1(line1, n);
            }
        }
        [CommandMethod("DD1")]
        public void DD1()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves)) return;
            Stopwatch stopwatch = Stopwatch.StartNew();
            stopwatch.Start();
            Dictionary<Curve, List<Point3d>> keyValuePairs = new Dictionary<Curve, List<Point3d>>();
            curves.ForEach(x => keyValuePairs.Add(x, new List<Point3d>()));
            for (int i = 0; i < curves.Count - 1; i++)
            {
                for (int j = i + 1; j < curves.Count; j++)
                {
                    List<Point3d> points = CmCurveMethod.IntersectWith(curves[i], curves[j], Intersect.OnBothOperands);
                    foreach (var item in points)
                    {
                        keyValuePairs[curves[i]].Add(item);
                        keyValuePairs[curves[j]].Add(item);
                    }
                }
            }
            List<Curve> curs = new List<Curve>();
            foreach (var item in keyValuePairs)
            {
                curs.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
            }
            EmEntityMethod.EraseEntities(curves);
            EmEntityMethod.AddEntities(curs);
            stopwatch.Stop();
            WCAD.Ed.WriteMessage(stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
        }
        [CommandMethod("DD2")]
        public void DD2()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves)) return;
            Stopwatch stopwatch = Stopwatch.StartNew();
            stopwatch.Start();
            Dictionary<Curve, List<Point3d>> keyValuePairs = new Dictionary<Curve, List<Point3d>>();
            curves.ForEach(x => keyValuePairs.Add(x, new List<Point3d>()));
            for (int i = 0; i < curves.Count - 1; i++)
            {
                Extents3d extents1 = curves[i].GeometricExtents;
                for (int j = i + 1; j < curves.Count; j++)
                {
                    Extents3d extents2 = curves[j].GeometricExtents;
                    if (extents1.ExtensHit(extents2))
                    {
                        List<Point3d> points = CmCurveMethod.IntersectWith(curves[i], curves[j], Intersect.OnBothOperands);
                        foreach (var item in points)
                        {
                            keyValuePairs[curves[i]].Add(item);
                            keyValuePairs[curves[j]].Add(item);
                        }
                    }

                }
            }
            List<Curve> curs = new List<Curve>();
            foreach (var item in keyValuePairs)
            {
                curs.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
            }
            EmEntityMethod.EraseEntities(curves);
            EmEntityMethod.AddEntities(curs);
            stopwatch.Stop();
            WCAD.Ed.WriteMessage(stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
        }
        [CommandMethod("DD3")]
        public void DD3()
        {
            object reactors = Application.GetSystemVariable("ACAD_REACTORS");
            if (!UmUserMethod.SelectEntities(out List<Circle> circles)) return;
            Stopwatch stopwatch = Stopwatch.StartNew();
            stopwatch.Start();
            Dictionary<Curve, List<Point3d>> keyValuePairs = new Dictionary<Curve, List<Point3d>>();
            Extents3d extents = EmEntityMethod.GetExtents3d(circles);
            QuadTreeNode<Circle> qtree = new QuadTreeNode<Circle>(extents.MinPoint.X, extents.MinPoint.Y, extents.MaxPoint.X - extents.MinPoint.X, extents.MaxPoint.Y - extents.MinPoint.Y, 100000);
            for (int i = 0; i < circles.Count; i++)
            {
                //这里只是添加了圆心，所以只能查找到圆心点。
                //你也可以添加圆的四个象限点。那么如果象限点满足条件，也可以找到。
                qtree.AddNode(circles[i].Center, circles[i]);
            }
            circles.ForEach(x => keyValuePairs.Add(x, new List<Point3d>()));
            for (int i = 0; i < circles.Count; i++)
            {
                List<Circle> cirsref = new List<Circle>();
                // 查找这个点周围100范围内的对象，用ref返回
                qtree.GetNodeRecRange(circles[i].Center, circles[i].Diameter, ref cirsref);
                for (int j = 0; j < cirsref.Count; j++)
                {
                    List<Point3d> points = CmCurveMethod.IntersectWith(circles[i], cirsref[j], Intersect.OnBothOperands);
                    foreach (var item in points)
                    {
                        keyValuePairs[circles[i]].Add(item);
                    }
                }
                //for (int j = i + 1; j < circles.Count; j++)
                //{
                //    if (circles[i].Center.DistanceTo(circles[j].Center)< circles[i].Radius*2)
                //    {
                //        List<Point3d> points = CmCurveMethod.GetIntersectPoints(circles[i], circles[j], Intersect.OnBothOperands);
                //        foreach (var item in points)
                //        {
                //            keyValuePairs[circles[i]].Add(item);
                //            keyValuePairs[circles[j]].Add(item);
                //        }
                //    }

                //}
            }
            List<Curve> curs = new List<Curve>();
            foreach (var item in keyValuePairs)
            {
                if (item.Value.Count == 0) continue;
                curs.AddRange(CmCurveMethod.GetSplitCurves(item.Key, item.Value));
            }
            EmEntityMethod.EraseEntities(circles);
            EmEntityMethod.AddEntities(curs);
            stopwatch.Stop();
            WCAD.Ed.WriteMessage(stopwatch.ElapsedMilliseconds.ToString() + "毫秒");
        }
        [CommandMethod("DD4")]
        public void DD4()
        {
            if (!UmUserMethod.GetEntity(out Ellipse ellipse)) return;
            double d = ellipse.GetDistAtPoint(ellipse.EndPoint);
            d /= 2;
            Point3d point = ellipse.GetPointAtDist(d);
            Point3d point1 = ellipse.GetPointAtDist(d / 2);
            Point3dCollection pos = new Point3dCollection();
            pos.Add(point);
            pos.Add(point1);
            var dbs = ellipse.GetSplitCurves(pos);
        }
        [CommandMethod("RRR")]
        public Field RRR()
        {
            BmBlcokMethod.GetBlockTableRecordByName("MyPoint", out BlockTableRecord btr);
            //if (!UmUserMethod.GetEntity(out BlockReference bl, "选择第一个图形")) return;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForWrite);
                if (bt.Has(btr.ObjectId))
                {
                    btr.ObjectId.GetObject(OpenMode.ForWrite);
                    foreach (var item in btr)
                    {
                        var s = item.GetObject(OpenMode.ForWrite);
                        if (s is AttributeDefinition att)
                        {
                            if (att.ExtensionDictionary != ObjectId.Null)
                            {
                                DBDictionary extDict = (DBDictionary)att.ExtensionDictionary.GetObject(OpenMode.ForWrite);
                                const string fldDictName = "ACAD_FIELD";
                                const string fldEntryName = "TEXT";
                                if (extDict.Contains(fldDictName))
                                {
                                    ObjectId fldDictId = extDict.GetAt(fldDictName);
                                    DBDictionary fldDict = (DBDictionary)fldDictId.GetObject(OpenMode.ForWrite);
                                    if (fldDict.Contains(fldEntryName))
                                    {
                                        ObjectId fldId = fldDict.GetAt(fldEntryName);
                                        var obj = fldId.GetObject(OpenMode.ForWrite);
                                        Field fld = obj as Field;
                                        return fld;
                                        //string fldCode = fld.GetFieldCode();
                                        //string sss = att.getTextWithFieldCodes();
                                    }
                                }
                            }

                        }

                    }

                }
                trans.Commit();
            }
            return null;
        }

        //[CommandMethod("RRRR")]
        public string RRRR()
        {

            if (!UmUserMethod.SelectEntities(out List<Entity> ents)) return "";
            Database database = BmBlcokMethod.Wblock(ents, EmEntityMethod.CenterPoint(ents));
            int n = 1;
            while (true)
            {
                string file = "DWG\\" + n.ToString() + ".dwg";
                if (!File.Exists(file)) break;
                n++;
            }
            database.SaveAs("DWG\\" + n.ToString() + ".dwg", DwgVersion.Current);
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();
            ObjectId id = ObjectId.Null;
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr = new BlockTableRecord();
                btr.Name = n.ToString();
                id = bt.Add(btr);
                tr.AddNewlyCreatedDBObject(btr, true);
                foreach (Entity ent in ents)
                {
                    Entity ent1 = ent.Clone() as Entity;
                    btr.AppendEntity(ent1);
                    tr.AddNewlyCreatedDBObject(ent1, true);
                }
                tr.Commit();
            }
            System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromHbitmap(Utils.GetBlockImage(id, 200, 200, Color.FromRgb(0, 0, 0)));
            bitmap.Save("DWG\\" + n.ToString() + ".png");
            using (var trans = WCAD.Trans)
            {
                id.GetObject(OpenMode.ForWrite).Erase();
                trans.Commit();
            }
            return n.ToString();
        }
        [CommandMethod("QAQ")]
        public void QAQ()
        {
            Window1 window1 = new Window1();
            Application.ShowModelessWindow(window1);
        }
        public void QR(string str)
        {
            WCAD.FocusDoc();
            using (WCAD.DocLock)
            {
                string blockName = System.IO.Path.GetFileNameWithoutExtension(str);
                if (!BmBlcokMethod.GetBlockTableRecordByName(blockName, out BlockTableRecord btr))
                {
                    BmBlcokMethod.InsertDwg(str, blockName);
                }
                BmBlcokMethod.GetBlockTableRecordByName(blockName, out btr);
                while (true)
                {
                    BlockReference block = new BlockReference(new Point3d(), btr.ObjectId);
                    JigAll jig = new JigAll(new Point3d(), (p) =>
                    {
                        List<Entity> entities = new List<Entity>();
                        block.Position = p;
                        entities.Add(block);
                        return entities;
                    });
                    if (WCAD.Ed.Drag(jig).Status == PromptStatus.OK)
                    {
                        EmEntityMethod.AddEntities(jig._ents);
                    }
                    else return;
                }

            }

        }
        [CommandMethod("QQQQ")]
        public void QQQQ()
        {
            //if (!UmUserMethod.GetString(out string str, "请输入整数，以,隔开")) return;
            string str = "15,14,13,12,9,16,8,5,6,17,7,3,2,20,19,1,11,10,18,4";
            List<int> nums = str.Split(',').Select(x => int.Parse(x)).ToList();
            List<Line> lines = new List<Line>();
            for (int i = 0; i < nums.Count; i++)
            {
                lines.Add(new Line(new Point3d(i, 0, 0), new Point3d(i, nums[i], 0)));
            }
            EmEntityMethod.AddEntities(lines);
            WCAD.Ed.GetDouble("");
            for (int i = 0; i < lines.Count - 1; i++)
            {
                for (int j = 0; j < lines.Count - 1 - i; j++)
                {
                    Line line1 = lines[j].Clone() as Line;
                    line1.ColorIndex = 1;
                    Line line2 = lines[j + 1].Clone() as Line;
                    line2.ColorIndex = 1;
                    EmEntityMethod.AddEntity(line1);
                    EmEntityMethod.AddEntity(line2);
                    WCAD.Ed.GetDouble("");
                    if (lines[j].Length > lines[j + 1].Length)
                    {
                        double d1 = lines[j].Length;
                        double d2 = lines[j + 1].Length;
                        EmEntityMethod.EditEntity(lines[j], () =>
                        {
                            lines[j].EndPoint += new Vector3d(0, d2 - d1, 0);
                        });
                        EmEntityMethod.EditEntity(lines[j + 1], () =>
                        {
                            lines[j + 1].EndPoint += new Vector3d(0, d1 - d2, 0);
                        });
                    }
                    EmEntityMethod.EraseEntity(line1);
                    EmEntityMethod.EraseEntity(line2);
                    WCAD.Ed.GetDouble("");
                }
            }
        }
        [CommandMethod("Q")]
        public void Q()
        {
            double[] s = new double[3];
            s[0] = 0;
            s[1] = 0;
            s[2] = 0;
            dynamic doc = WCAD.Doc.GetAcadDocument();
            doc.Import(@"C:\Program Files (x86)\AutoCAD 2008\Help\newfeatures\05 Floor Plan-Model.dwf", s, 1);
            if (!UmUserMethod.SelectEntities(out List<DBText> dbtexts)) return;

            doc.Export("1", "wmf", doc.ActiveSelectionSet);
            var ss = doc.ActiveViewport.LowerLeftCorner;

            dynamic b = doc.Import("1.wmf", s, 2);

            long id = b.ObjectID;
            ObjectId objectId = new ObjectId(new IntPtr(id));
            BlockReference block = objectId.ToEntity<BlockReference>();
            EmEntityMethod.EditEntity(block, () =>
            {
                block.Position += EmEntityMethod.GetExtents3d(dbtexts).MinPoint - block.GeometricExtents.MinPoint;
            });
        }
        [CommandMethod("S")]
        public void S()
        {
            //var ss= IUtils.ExtractBorderEntities(WCAD.Db);
            //foreach (ObjectId item in ss)
            //{
            //    Entity entity = item.ToEntity();
            //}
            //string str = IUtils.GetVersionString();
            //using (WCAD.Trans)
            //{
            //    BlockTable block = WCAD.Db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
            //    var sss = EmEntityMethod.GetExtents3d(UmUserMethod.SelectAllEntities<Entity>());
            //    int width =(int)( sss.MinPoint.X - sss.MinPoint.X);
            //    int height = (int)( sss.MinPoint.Y - sss.MinPoint.Y);
            //    System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromHbitmap(Utils.GetBlockImage(block[BlockTableRecord.ModelSpace], width,height, Autodesk.AutoCAD.Colors.Color.FromRgb(0, 0, 0)));
            //    bitmap.Save("2222.png");
            //}

            //if (!UmUserMethod.GetEntity(out MText mText)) return;
            //string str= IUtils.GetStrippedMTextContents(mText);
            //if (!UmUserMethod.GetEntity(out BlockReference block)) return;
            //if (!UmUserMethod.GetEntity(out BlockReference block2)) return;

            //Database db = HostApplicationServices.WorkingDatabase;
            //using (Transaction tran = db.TransactionManager.StartTransaction())
            //{
            //    block.ObjectId.GetObject(OpenMode.ForWrite, false);
            //    ConnectionPointReferenceUtil connection = new ConnectionPointReferenceUtil(block);
            //    var ss = connection.GetProperties();
            //    connection.SetProperty("1", "3");
            //}
            ////ConnectionPointManager.Connect(block1, block2);
            //AdaptiveBitmap bitmap = new AdaptiveBitmap(new Uri(@"C:\Users\Administrator\Pictures\aaa.jpg"));

            //bitmap.BeginAnimation(System.Windows.DependencyProperty.UnsetValue, new AnimationTimeline());
            //Database database = new Database();
            ////database.ReadDwgFile(@"C:\Users\Administrator\Desktop\222.dwg", System.IO.FileShare.Read, true, "");
            //WorkerParams workerParams = new WorkerParams(@"C:\Program Files (x86)\AutoCAD 2008\Help\newfeatures\05 Floor Plan-Model.dwf", @"C:\Program Files (x86)\AutoCAD 2008\Help\newfeatures\05 Floor Plan-Model.dwf");
            //var ss = IUtils.DnWFToF2DAutoCommandGuts(workerParams, HostApplicationServices.WorkingDatabase, true);
            //WorkerMessenger workerMessenger = new WorkerMessenger();
            //var sss = IUtils.RunDWFToF2DConverterDwg(workerMessenger, workerParams);
            //  if (!UmUserMethod.GetEntity(out Entity ent)) return;
            //var ss= IUtils.GetObjectName(ent);
            //Database database = new Database();
            //database.ReadDwgFile(@"C:\Users\Administrator\Desktop\22.dwg", System.IO.FileShare.Read, true, "");
            //IUtils.SendHeartbeat();
            if (!UmUserMethod.GetEntity(out Circle circle)) return;
            if (!UmUserMethod.GetPoint(out Point3d point)) return;
            JigJig jig = new JigJig(point, (p, e1, e2) =>
            {
                Circle circle1 = circle.Clone() as Circle;
                circle1.Center += p - point;
                e1.Add(circle1);
            });
            List<string> strs = new List<string>();
            //strs.Count= 0;
        }

        [CommandMethod("CURDIR")]
        public void GetCurrentDirectory()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            ed.WriteMessage("\nSystem.Environment.CurrentDirectory: " + System.Environment.CurrentDirectory + "\nSystem.IO.Directory.GetCurrentDirectory(): " + System.IO.Directory.GetCurrentDirectory());
        }
        [CommandMethod("MMMMM")]
        public void MMMMM()
        {
            if (!UmUserMethod.GetEntity(out BlockReference bl)) return;
            Line line = new Line(bl.GeometricExtents.MinPoint, bl.GeometricExtents.MaxPoint);
            EmEntityMethod.AddEntity(line);
            if (!UmUserMethod.SelectEntities(out List<DBPoint> points)) return;
            if (!UmUserMethod.SelectEntities(out List<Polyline> pls)) return;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            MPolygon mPolygon = new MPolygon();
            foreach (var pl in pls)
            {
                mPolygon.AppendLoopFromBoundary(pl, false, 0);

            }
            EmEntityMethod.EditEntities(points, () =>
            {
                foreach (var item in points)
                {
                    var ss = mPolygon.IsPointInsideMPolygon(item.Position, 0);
                    if (mPolygon.IsPointInsideMPolygon(item.Position, 0).Count == 1)
                    {
                        item.ColorIndex = 1;
                    }
                }
            });
            stopwatch.Stop();
            WCAD.Ed.WriteMessage("用时:" + stopwatch.ElapsedMilliseconds + "毫秒");
            //var r1 = Application.DocumentManager.MdiActiveDocument.Editor.GetSelection();
            //var a = r1.Value[0];
            //List<Point3d> points = new List<Point3d>();
            //if (a is CrossingOrWindowSelectedObject c)
            //{
            //    foreach (PickPointDescriptor item in c.GetPickPoints())
            //    {
            //        points.Add(item.PointOnLine);
            //        it
            //    }
            //}
            //Line line1 = r1.Value.GetObjectIds()[0].ToEntity() as Line;
            //Line line2 = r1.Value.GetObjectIds()[1].ToEntity() as Line;
            //Point3d point = points[0];
            //Point3d p1 = new Point3d();
            //Point3d p2 = new Point3d();
            //if (line1.StartPoint.DistanceTo(point) < line1.EndPoint.DistanceTo(point))
            //{
            //    p1 = line1.StartPoint;
            //}
            //else
            //{
            //    p1 = line1.EndPoint;
            //}
            //if (line2.StartPoint.DistanceTo(point) < line2.EndPoint.DistanceTo(point))
            //{
            //    p2 = line2.StartPoint;
            //}
            //else
            //{
            //    p2 = line2.EndPoint;
            //}
            //Line line = new Line(p1, p2);
            //EmEntityMethod.AddEntity(line);
            //if (!UmUserMethod.SelectEntities(out List<Line> lines)) return;
            //Line line1 = lines[0];
            //Line line2 = lines[1];
            //JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
            //{
            //    Point3d p1 = new Point3d();
            //    Point3d p2 = new Point3d();
            //    if (line1.StartPoint.DistanceTo(p) < line1.EndPoint.DistanceTo(p))
            //    {
            //        p1 = line1.StartPoint;
            //    }
            //    else
            //    {
            //        p1 = line1.EndPoint;
            //    }
            //    if (line2.StartPoint.DistanceTo(p) < line2.EndPoint.DistanceTo(p))
            //    {
            //        p2 = line2.StartPoint;
            //    }
            //    else
            //    {
            //        p2 = line2.EndPoint;
            //    }
            //    Line line = new Line(p1, p2);
            //    e1.Add(line);
            //});
        }
        [CommandMethod("NNNN")]
        public void NNNNN()
        {
            if (!UmUserMethod.GetEntity(out Polyline pl1)) return;
            if (!UmUserMethod.GetEntity(out Polyline pl2)) return;
            MPolygon mPolygon = new MPolygon();
            mPolygon.AppendLoopFromBoundary(pl1, false, 0);
            for (int i = 0; i < pl2.NumberOfVertices; i++)
            {
                if (mPolygon.IsPointInsideMPolygon(pl2.GetPoint3dAt(i), 0).Count == 1)
                {
                    WCAD.Ed.WriteMessage("有重叠");
                    return;
                }
            }
            mPolygon = new MPolygon();
            mPolygon.AppendLoopFromBoundary(pl2, false, 0);
            for (int i = 0; i < pl1.NumberOfVertices; i++)
            {
                if (mPolygon.IsPointInsideMPolygon(pl1.GetPoint3dAt(i), 0).Count == 1)
                {
                    WCAD.Ed.WriteMessage("有重叠");
                    return;
                }
            }
            WCAD.Ed.WriteMessage("没有重叠");
        }
        [CommandMethod("HHH")]
        public void HHH()
        {
            List<Circle> circles = new List<Circle>();
            Polyline pl = PmPolylineMethod.CreatePolyline(new List<Point3d>() { new Point3d(0, 0, 0), new Point3d(100, 0, 0), new Point3d(100, 100, 0), new Point3d(0, 100, 0) });
            MPolygon mPolygon = new MPolygon();
            mPolygon.AppendLoopFromBoundary(pl, false, 0);
            Random random = new Random();
            for (int i = 0; i < 100; i++)
            {
                double x = random.NextDouble() * 100;
                double y = random.NextDouble() * 100;
                Point3d center = new Point3d(x, y, 0);

                // 创建圆并添加到模型空间中
                Circle circle = new Circle(center, Vector3d.ZAxis, 0.1);
                circles.Add(circle);
            }
            //EmEntityMethod.AddEntities(circles);
            JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
            {
                e2.Add(pl);
                foreach (var circle in circles)
                {
                    Vector3d vector = new Vector3d(1, 0, 0);
                    vector = vector.RotateBy(random.NextDouble() * 360.0 / 180.0 * Math.PI, Vector3d.ZAxis);
                    var ss = circle.Center;
                    circle.Center += vector;
                    if (mPolygon.IsPointInsideMPolygon(circle.Center, 0).Count != 1)
                    {
                        circle.Center = ss;
                    }
                }
                e2.AddRange(circles);

            });

        }
        [CommandMethod("Print")]
        public void Print1()
        {
            if (!UmUserMethod.GetEntity(out Entity ent)) return;
            ent.Print();
        }
        [CommandMethod("PrintTwo")]
        public void PrintTwo()
        {
            if (!UmUserMethod.GetEntity(out Entity ent1)) return;
            if (!UmUserMethod.GetEntity(out Entity ent2)) return;
            if (ent1.GetType() != ent2.GetType()) return;
            Dictionary<string, string> keyValues1 = ent1.GetProperties();
            Dictionary<string, string> keyValues2 = ent2.GetProperties();
        }
        [CommandMethod("P")]
        public void P()
        {
            //dynamic bt =HostApplicationServices.WorkingDatabase.BlockTableId;
            //dynamic btr = bt[BlockTableRecord.ModelSpace];
            //foreach (dynamic item in btr)
            //{
            //    item.ColorIndex = 1;
            //}
            dynamic id = Application.DocumentManager.MdiActiveDocument.Editor.GetEntity("").ObjectId;
            id.ColorIndex = 1;
        }
        [CommandMethod("PP")]
        public void PP()
        {
            //dynamic bt =HostApplicationServices.WorkingDatabase.BlockTableId;
            //dynamic btr = bt[BlockTableRecord.ModelSpace];
            //foreach (dynamic item in btr)
            //{
            //    item.ColorIndex = 1;
            //}
            //dynamic id = Application.DocumentManager.MdiActiveDocument.Editor.GetEntity("").ObjectId;
            //id.AttributeCollection["1"].TextString = "2";

            //foreach (dynamic item in id.AttributeCollection)
            //{
            //    if (item.Tag == "1")
            //    {
            //        item.TextString = "2";
            //    }
            //}
            List<Point3d> points = new List<Point3d>();
            points.Add(new Point3d(1, 1, 1));
            points.Add(new Point3d(2, 2, 2));
            points.Add(new Point3d(3, 3, 3));
            List<Point2d> point2s = points.Cast<Point2d>().ToList();

        }
        [CommandMethod("Arrow")]
        public void Arrow()
        {
            if (!UmUserMethod.GetPoint(out Point3d point, "起点")) return;
            JigJig jig = new JigJig(point, (p, e1, e2) =>
            {
                Vector3d vector = point - p;
                Vector3d vector1 = vector.RotateBy(Math.PI / 6, Vector3d.ZAxis) / 10;
                Vector3d vector2 = vector.RotateBy(Math.PI / 6, -Vector3d.ZAxis) / 10;
                Point3d p1 = p + vector1;
                Point3d p2 = p + vector2;
                List<Point3d> points = new List<Point3d>();
                points.Add(point);
                points.Add(p);
                points.Add(p1);
                points.Add(p);
                points.Add(p2);
                points.Add(p);
                Polyline pl = PmPolylineMethod.CreatePolyline(points, false);
                pl.ColorIndex = 1;
                e1.Add(pl);
            }, message: "终点");
        }
        [CommandMethod("BBO")]
        public void BBO()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curve, "框选识别外轮廓的图形")) return;
            List<Line> lines = new List<Line>();
            foreach (var item in curve)
            {
                if (item is Line) lines.Add(item as Line);//直线直接添加
                else if (item is Polyline pl)
                {
                    List<Curve> cus = PmPolylineMethod.ExplodePolyline(pl);//多段线炸开，添加直线
                    foreach (var cu in cus)
                    {
                        if (cu is Line) lines.Add(cu as Line);
                    }
                }
            }
            //lines.ForEach(line => line.ColorIndex = 1);
            //EmEntityMethod.AddEntities(lines);
            Dictionary<Line, List<Point3d>> pointsOnLine = new Dictionary<Line, List<Point3d>>();//直线和交点的键值对
            foreach (var item in lines)
            {
                pointsOnLine.Add(item, new List<Point3d>());//初始化
            }
            for (int i = 0; i < lines.Count - 1; i++)
            {
                for (int j = i + 1; j < lines.Count; j++)
                {
                    Point3dCollection pos = new Point3dCollection();
                    lines[i].IntersectWith(lines[j], Intersect.OnBothOperands, pos, IntPtr.Zero, IntPtr.Zero);
                    if (pos.Count > 0)
                    {
                        foreach (Point3d item in pos)
                        {
                            pointsOnLine[lines[i]].Add(item);
                            pointsOnLine[lines[j]].Add(item);
                        }
                    }
                }
            }
            lines.Clear();
            foreach (var item in pointsOnLine)
            {
                Line line = item.Key;
                List<Point3d> points = item.Value;
                if (points.Count == 0)
                {
                    lines.Add(line);
                }
                else
                {
                    if (points.Count > 1)
                    {
                        points = points.OrderBy(x => line.GetParameterAtPoint(x)).ToList();
                    }
                    Point3dCollection pos = new Point3dCollection();
                    points.ForEach(x => pos.Add(x));
                    DBObjectCollection dbs = line.GetSplitCurves(pos);
                    foreach (var dbobject in dbs)
                    {
                        if (dbobject is Line)
                        {
                            lines.Add(dbobject as Line);
                        }
                    }
                }
            }
            //lines.ForEach(line => line.ColorIndex = 1);
            //EmEntityMethod.AddEntities(lines);
            if (!UmUserMethod.GetPoint(out Point3d point, "请选择外面一点")) return;
            Line firstLine = lines.OrderBy(x => x.GetClosestPointTo(point, false).DistanceTo(point)).First();
            //firstLine.ColorIndex = 1;
            //EmEntityMethod.AddEntity(firstLine);
            lines.Remove(firstLine);
            Polyline polyline = new Polyline();
            polyline.AddVertexAt(0, firstLine.StartPoint.Convert2d(new Plane()), 0, 0, 0);
            polyline.AddVertexAt(1, firstLine.EndPoint.Convert2d(new Plane()), 0, 0, 0);
            Vector3d v1 = firstLine.StartPoint - point;
            Vector3d v2 = firstLine.EndPoint - point;
            if (v1.CrossProduct(v2).Z > 0) polyline.ReverseCurve();
            //polyline.ColorIndex = 1;
            //EmEntityMethod.AddEntity(polyline);
            while (true)
            {
                List<Line> tmps = new List<Line>();
                foreach (var item in lines)
                {
                    if (item.StartPoint == polyline.EndPoint)
                    {
                        tmps.Add(item);
                    }
                    else if (item.EndPoint == polyline.EndPoint)
                    {
                        item.ReverseCurve();
                        tmps.Add(item);
                    }
                }
                if (tmps.Count == 0) break;
                Vector3d vector = -polyline.GetFirstDerivative(polyline.EndPoint);
                double maxAngle = 0;
                Line bigLine = new Line();
                foreach (var item in tmps)
                {
                    double angle = vector.GetAngleTo(item.Delta, -Vector3d.ZAxis);
                    if (angle > maxAngle)
                    {
                        maxAngle = angle;
                        bigLine = item;
                    }
                }
                polyline.JoinEntity(bigLine);
                lines.Remove(bigLine);
                if (polyline.EndPoint == polyline.StartPoint) break;
            }
            polyline.ColorIndex = 1;

            WWE(polyline);
            //EmEntityMethod.AddEntity(polyline);
        }
        [CommandMethod("TZ")]
        public void TZ()
        {
            List<DBText> dBTexts = UmUserMethod.SelectAllEntities<DBText>();
            dBTexts = dBTexts.FindAll(x => x.Layer == "TH_TEXT");
            //WCAD.Ed.WriteMessage(dBTexts.Count.ToString());
            // 创建 OpenFileDialog 对象
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置对话框的标题和过滤器
            openFileDialog.Title = "选择要打开的文件";
            openFileDialog.Filter = "Excel文件 (*.xls)|*.xls|所有文件 (*.*)|*.*";

            // 打开对话框并检查用户是否选择了文件
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 通过对话框获取选定文件的路径
                string filePath = openFileDialog.FileName;

                // 在此处添加打开文件的代码

                ExcelMethod.OpenExcel(filePath, false);
                WCAD.FocusDoc();
                List<string> strs = new List<string>();
                for (int i = 2; i < 1000; i++)
                {
                    if (ExcelMethod.GetCell(i, 1) == null)
                    {
                        break;
                    }
                    else
                    {
                        strs.Add(ExcelMethod.GetCell(i, 1).ToString());
                    }
                }
                ExcelMethod.Quit();
                List<int> ints = new List<int>();
                for (int i = 0; i < strs.Count; i++)
                {
                    string str = strs[i];
                    if (strs.Count(x => x == str) > 1) ints.Add(i);
                }
                if (ints.Count > 0)
                {
                    StringBuilder sb = new StringBuilder("提资单中第");
                    foreach (var item in ints)
                    {
                        sb.Append((item + 2).ToString() + "、");
                    }
                    sb.Append("行重复");
                    sb.Replace("、行", "行");
                    WCAD.Ed.WriteMessage(sb.ToString() + "\n");
                }
                else
                {
                    WCAD.Ed.WriteMessage("提资单无重复" + "\n");
                }
                List<string> texts = new List<string>();
                strs = strs.Distinct().ToList();
                foreach (var item in strs)
                {
                    if (dBTexts.All(x => x.TextString != item))
                    {
                        texts.Add(item);
                    }
                }
                if (texts.Count > 0)
                {
                    StringBuilder sb = new StringBuilder("图中缺少 ");
                    foreach (var item in texts)
                    {
                        sb.Append(item + "、");
                    }
                    sb.Append("设备编号");
                    sb.Replace("、设备编号", "设备编号");
                    WCAD.Ed.WriteMessage(sb.ToString() + "\n");
                }
                else
                {
                    WCAD.Ed.WriteMessage("图中无缺少设备编号" + "\n");
                }
                bool b = false;
                foreach (var item in dBTexts)
                {

                    if (dBTexts.Count(x => x.TextString == item.TextString) > 1)
                    {
                        Polyline polyline = PmPolylineMethod.CreatePolylineByExtents3d(item.GeometricExtents);
                        polyline.AddVertexAt(4, item.GeometricExtents.MinPoint.Convert2d(new Plane()), 0, 0, 0);
                        polyline.AddVertexAt(5, new Point2d(), 0, 0, 0);
                        polyline.ColorIndex = 1;
                        EmEntityMethod.AddEntity(polyline);
                        b = true;
                    }
                }
                if (b)
                {
                    WCAD.Ed.WriteMessage("图中设备编号有重复,已在图中标出" + "\n");

                }
                else
                {
                    WCAD.Ed.WriteMessage("图中设备编号无重复" + "\n");

                }
            }


        }
        [CommandMethod("BBBO")]
        public void BBBO()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curve, "框选识别外轮廓的图形")) return;
            List<Line> lines = new List<Line>();
            foreach (var item in curve)
            {
                if (item is Line) lines.Add(item as Line);//直线直接添加
                else if (item is Polyline pl)
                {
                    List<Curve> cus = PmPolylineMethod.ExplodePolyline(pl);//多段线炸开，添加直线
                    foreach (var cu in cus)
                    {
                        if (cu is Line) lines.Add(cu as Line);
                    }
                }
            }

            ////lines.ForEach(line => line.ColorIndex = 1);
            ////EmEntityMethod.AddEntities(lines);
            //Dictionary<Line, List<Point3d>> pointsOnLine = new Dictionary<Line, List<Point3d>>();//直线和交点的键值对
            //foreach (var item in lines)
            //{
            //    pointsOnLine.Add(item, new List<Point3d>());//初始化
            //}
            //for (int i = 0; i < lines.Count - 1; i++)
            //{
            //    for (int j = i + 1; j < lines.Count; j++)
            //    {
            //        Point3dCollection pos = new Point3dCollection();
            //        lines[i].IntersectWith(lines[j], Intersect.OnBothOperands, pos, IntPtr.Zero, IntPtr.Zero);
            //        if (pos.Count > 0)
            //        {
            //            foreach (Point3d item in pos)
            //            {
            //                pointsOnLine[lines[i]].Add(item);
            //                pointsOnLine[lines[j]].Add(item);
            //            }
            //        }
            //    }
            //}
            //lines.Clear();
            //foreach (var item in pointsOnLine)
            //{
            //    Line line = item.Key;
            //    List<Point3d> points = item.Value;
            //    if (points.Count == 0)
            //    {
            //        lines.Add(line);
            //    }
            //    else
            //    {
            //        if (points.Count > 1)
            //        {
            //            points = points.OrderBy(x => line.GetParameterAtPoint(x)).ToList();
            //        }
            //        Point3dCollection pos = new Point3dCollection();
            //        points.ForEach(x => pos.Add(x));
            //        DBObjectCollection dbs = line.GetSplitCurves(pos);
            //        foreach (var dbobject in dbs)
            //        {
            //            if (dbobject is Line)
            //            {
            //                lines.Add(dbobject as Line);
            //            }
            //        }
            //    }
            //}
            ////lines.ForEach(line => line.ColorIndex = 1);
            ////EmEntityMethod.AddEntities(lines);
            //if (!UmUserMethod.GetPoint(out Point3d point, "请选择外面一点")) return;
            //Line firstLine = lines.OrderBy(x => x.GetClosestPointTo(point, false).DistanceTo(point)).First();
            ////firstLine.ColorIndex = 1;
            ////EmEntityMethod.AddEntity(firstLine);
            //lines.Remove(firstLine);
            //Polyline polyline = new Polyline();
            //polyline.AddVertexAt(0, firstLine.StartPoint.Convert2d(new Plane()), 0, 0, 0);
            //polyline.AddVertexAt(1, firstLine.EndPoint.Convert2d(new Plane()), 0, 0, 0);
            //Vector3d v1 = firstLine.StartPoint - point;
            //Vector3d v2 = firstLine.EndPoint - point;
            //if (v1.CrossProduct(v2).Z > 0) polyline.ReverseCurve();
            ////polyline.ColorIndex = 1;
            ////EmEntityMethod.AddEntity(polyline);
            //while (true)
            //{
            //    List<Line> tmps = new List<Line>();
            //    foreach (var item in lines)
            //    {
            //        if (item.StartPoint == polyline.EndPoint)
            //        {
            //            tmps.Add(item);
            //        }
            //        else if (item.EndPoint == polyline.EndPoint)
            //        {
            //            item.ReverseCurve();
            //            tmps.Add(item);
            //        }
            //    }
            //    if (tmps.Count == 0) break;
            //    Vector3d vector = -polyline.GetFirstDerivative(polyline.EndPoint);
            //    double maxAngle = 0;
            //    Line bigLine = new Line();
            //    foreach (var item in tmps)
            //    {
            //        double angle = vector.GetAngleTo(item.Delta, -Vector3d.ZAxis);
            //        if (angle > maxAngle)
            //        {
            //            maxAngle = angle;
            //            bigLine = item;
            //        }
            //    }
            //    polyline.JoinEntity(bigLine);
            //    lines.Remove(bigLine);
            //    if (polyline.EndPoint == polyline.StartPoint) break;
            //}
            //polyline.ColorIndex = 1;
            //EmEntityMethod.AddEntity(polyline);
        }

        [CommandMethod("BOBO")]
        public void BOBO()
        {
            //Editor editor = Application.DocumentManager.MdiActiveDocument.Editor;
            //editor.Command("rectang");
            //editor.Command("revcloud","", WCAD.Ed.SelectLast().Value,"");
            Line line1 = new Line(new Point3d(0, 0, 0), new Point3d(1, 0, 0));
            Line line2 = new Line(new Point3d(0, 1, 0), new Point3d(1, 1, 0));

            var ss = line1.GetGeCurve().GetClosestPointTo(line2.GetGeCurve());
        }
        [CommandMethod("GE")]
        public void GE()
        {
            UmUserMethod.GetEntity(out Entity ent);
        }
        [CommandMethod("JIG")]
        public void JIG()
        {
            if (!UmUserMethod.GetEntity(out Line line)) return;
            Line line1 = line.Clone() as Line;
            Line line2 = line.Clone() as Line;
            line1.Color = Color.FromRgb(69, 76, 83);
            EmEntityMethod.EraseEntity(line);
            JigJig jig = new JigJig(line.EndPoint, (p, e1, e2) =>
            {
                e2.Add(line1);
                line2.EndPoint = p;
                e1.Add(line2);
            });

        }
        [CommandMethod(nameof(Cloud))]
        public void Cloud()
        {
            List<string> strs = new List<string>();
            for (int i = 0; i < strs.Count; i++)
            {

            }






        }


        [CommandMethod("PPY")]
        public void PPY()
        {
            if (!UmUserMethod.GetEntity(out Polyline p1)) return;
            EmEntityMethod.AddEntity(p1.GetOffsetCurves(5)[0] as Polyline);
        }
        [CommandMethod("YUY")]
        public void YUY()
        {
            //if (!UmUserMethod.GetEntity(out BlockReference bl)) return;
            if (!UmUserMethod.GetDouble(out double dis, "请输出长度")) return;
            BmBlcokMethod.GetBlockTableRecordByName("基础", out BlockTableRecord btr1);
            BlockReference bl = new BlockReference(Point3d.Origin, btr1.ObjectId);
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tran = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite);

                var id = btr.AppendEntity(bl);
                tran.AddNewlyCreatedDBObject(bl, true);

                DynamicBlockReferencePropertyCollection dynProperties = bl.DynamicBlockReferencePropertyCollection;

                foreach (DynamicBlockReferenceProperty property in dynProperties)
                {
                    if (property.ReadOnly)
                    {
                        continue;
                    }
                    string name = property.PropertyName;
                    if (name == "距离1")
                    {
                        property.Value = dis;
                    }
                    if (name == "距离2")
                    {
                        property.Value = 200.0;
                    }
                }
                tran.Commit();
            }
            //BmBlcokMethod.SetDynBlockValue(bl, "距离1", dis);
        }
        [CommandMethod("Youshou")]
        public void Youshou()
        {
            //if (!UmUserMethod.GetEntity(out Arc circle)) return;

            if (!UmUserMethod.GetEntity(out Line line1)) return;
            if (!UmUserMethod.GetEntity(out Line line2)) return;
            Vector3d vector = line1.Delta.CrossProduct(line2.Delta);
            vector = vector.GetNormal() * line1.Length * 0.8;
            BlockReference bl = mesh.Clone() as BlockReference;
            bl.Position = line1.StartPoint;
            //bl.ScaleFactors= new Scale3d(line1.Length, line1.Length, line1.Length);
            EmEntityMethod.AddEntity(bl);
            //var ss = PmPolylineMethod.GetYoushouByVector(line1.StartPoint, vector);
            //EmEntityMethod.AddEntities(ss);
        }
        BlockReference mesh;
        [CommandMethod("CC")]
        public void CC()
        {
            DBText text = new DBText();
            text.TextString = "白老师牛逼！！";
            text.ColorIndex = 2;
            text.SetDatabaseDefaults();
            text.AdjustAlignment(WCAD.Db);
            JigPromptPointOptions jppo = new JigPromptPointOptions();
            jppo.Keywords.Add("A", "A", "旋转90°(A)");
            jppo.Keywords.Add("+", "+", "放大(+)");
            jppo.Keywords.Add("-", "-", "缩小(-)");
            JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
            {
                text.Position = p;
                e1.Add(text);
            }, jppo);
            using (SingleKeyWordHook skwh = new SingleKeyWordHook())
            {
                skwh.AddKeys(jppo.Keywords);
                while (true)
                {
                    skwh.Reset();
                    PromptResult r1 = WCAD.Ed.Drag(jig);
                    if (skwh.IsResponsed || r1.Status == PromptStatus.Keyword)
                    {
                        //WCAD.Ed.WriteMessage(skwh.StringResult);
                        switch (skwh.IsResponsed ? skwh.StringResult : r1.StringResult.ToUpper())
                        {
                            case "A":
                                text.Rotation += Math.PI / 10;
                                break;
                            case "ADD":
                                text.Height *= 1.1;
                                break;
                            case "SUBTRACT":
                                text.Height *= 0.9;
                                break;
                            default:
                                break;
                        }
                        continue;
                    }
                    if (r1.Status == PromptStatus.OK)
                    {
                        EmEntityMethod.AddEntity(text);
                        break;
                    }
                }
            }


        }
        [CommandMethod("BWH")]
        public void BWH()
        {
            if (!UmUserMethod.SelectEntities(out List<Entity> ents)) return;
            Extents3d extents = EmEntityMethod.GetExtents3d(ents);
            Line line = new Line(extents.MinPoint, extents.MaxPoint);
            EmEntityMethod.AddEntity(line);
        }
        [CommandMethod("C")]
        public void C()
        {
            if (!UmUserMethod.GetPoint(out Point3d point, "选择内部点")) return;
            if (!UmUserMethod.GetDouble(out double fx, "输入缝隙间距")) return;
            double minx = 317.3632;
            double maxx = 1533.963;
            double miny = 18.0;
            double maxy = 382.0;
            double w = maxx - minx;
            double h = maxy - miny;
            int n = 5;
            List<Polyline> pls = new List<Polyline>();
            JigPromptPointOptions jppo = new JigPromptPointOptions();
            jppo.Keywords.Add("+", "+", "增加柜门(+)");
            jppo.Keywords.Add("-", "-", "减少柜门(-)");

            JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
            {
                Point3d p1 = new Point3d(minx + fx, maxy, 0);
                Point3d p2 = new Point3d(minx + fx, miny, 0);
                pls = new List<Polyline>();
                for (int i = 0; i < n; i++)
                {
                    double x = minx + (w - fx) / n * (i + 1);
                    Point3d p3 = new Point3d(x, miny, 0);
                    Point3d p4 = new Point3d(x, maxy, 0);
                    Polyline pl = PmPolylineMethod.CreatePolyline(new List<Point3d>() { p1, p2, p3, p4 }, true);
                    p1 = p4 + new Vector3d(fx, 0, 0);
                    p2 = p3 + new Vector3d(fx, 0, 0);
                    pls.Add(pl);
                }
                e1.AddRange(pls);
            }, jppo);
            using (SingleKeyWordHook skwh = new SingleKeyWordHook())
            {
                skwh.AddKeys(jppo.Keywords);
                while (true)
                {
                    skwh.Reset();
                    PromptResult r1 = WCAD.Ed.Drag(jig);
                    if (skwh.IsResponsed || r1.Status == PromptStatus.Keyword)
                    {
                        //WCAD.Ed.WriteMessage(skwh.StringResult);
                        switch (skwh.IsResponsed ? skwh.StringResult : r1.StringResult.ToUpper())
                        {
                            case "ADD":
                                n++;
                                break;
                            case "SUBTRACT":
                                if (n > 1)
                                {
                                    n--;
                                }
                                break;
                            default:
                                break;
                        }
                        continue;
                    }
                    if (r1.Status == PromptStatus.OK)
                    {
                        EmEntityMethod.AddEntities(pls);
                        break;
                    }
                }
            }
        }
        [CommandMethod("TTR")]
        public void TTR()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves)) return;
            if (!UmUserMethod.GetEntity(out Polyline pl)) return;
            if (!UmUserMethod.GetPoint(out Point3d point)) return;
            Point3d p = pl.GetClosestPointTo(point, false);
            Vector3d vector = pl.GetFirstDerivative(p);
            double z = vector.CrossProduct(point - p).Z;
            z = Math.Sign(z);
            if (curves.Contains(pl)) curves.Remove(pl);
            List<Curve> result = new List<Curve>();
            foreach (var curve in curves)
            {
                Point3dCollection pos = new Point3dCollection();
                curve.IntersectWith(pl, Intersect.OnBothOperands, pos, IntPtr.Zero, IntPtr.Zero);
                List<Curve> curs = new List<Curve>();
                if (pos.Count == 0) curs.Add(curve);
                else
                {
                    List<Point3d> points = new List<Point3d>();
                    foreach (Point3d item in pos)
                    {
                        points.Add(item);
                    }
                    points = points.OrderBy(x => curve.GetParameterAtPoint(x)).ToList();
                    pos.Clear();
                    points.ForEach(x => pos.Add(x));
                    DBObjectCollection dbs = curve.GetSplitCurves(pos);
                    foreach (Curve item in dbs)
                    {
                        curs.Add(item);
                    }
                }
                foreach (var item in curs)
                {
                    point = item.GetPointAtDist(0.01);
                    p = pl.GetClosestPointTo(point, false);
                    vector = pl.GetFirstDerivative(p);
                    double zz = vector.CrossProduct(point - p).Z;
                    zz = Math.Sign(zz);
                    if (zz * z > 0) result.Add(item);
                }
            }
            result = result.Distinct().ToList();
            EmEntityMethod.EraseEntities(curves);
            EmEntityMethod.AddEntities(result);
        }
        [CommandMethod("BS")]
        public void BS()
        {
            if (!UmUserMethod.GetEntity(out Table table)) return;
            Autodesk.AutoCAD.Windows.ColorDialog color = new Autodesk.AutoCAD.Windows.ColorDialog();
            var ss = color.ShowDialog();

            EmEntityMethod.EditEntity(table, () =>
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        Cell cell = table.Cells[i, j];

                        cell.ContentColor = color.Color;

                    }
                }
            });
            //if (!CADWindows.SelectPlotStyle(out string color)) return;
            //WCAD.Ed.WriteMessage(color);
        }
        [CommandMethod("CX")]
        public void CX()
        {
            if (!UmUserMethod.GetPoint(out Point3d point, "选择点")) return;
            List<Curve> curves = UmUserMethod.SelectAllEntities<Curve>();
            List<Curve> curs = new List<Curve>();
            for (int i = 0; i < 360; i++)
            {
                Ray ray = new Ray();
                ray.BasePoint = point;
                Vector3d vector = new Vector3d(1, 0, 0);
                vector = vector.RotateBy(Math.PI / 180 * i, Vector3d.ZAxis);
                ray.UnitDir = vector;
                ray.BasePoint = point;
                ray.UnitDir = vector;
                double dis = double.MaxValue;
                Point3d pp = new Point3d();
                foreach (Curve item in curves)
                {
                    Point3dCollection pos = new Point3dCollection();
                    item.IntersectWith(ray, Intersect.OnBothOperands, pos, IntPtr.Zero, IntPtr.Zero);
                    if (pos.Count == 0) continue;
                    foreach (Point3d po in pos)
                    {
                        double tmp = po.DistanceTo(point);
                        if (tmp < dis)
                        {
                            dis = tmp;
                            pp = po;
                        }
                    }

                }

                curs.Add(new Line(point, pp));
            }
            EmEntityMethod.AddEntities(curs);
        }
        [CommandMethod("CXX")]
        public void CXX()
        {
            //if (!UmUserMethod.GetEntity(out Circle circle)) return;
            //List<Entity> entities = UmUserMethod.SelectAllEntities<Entity>();
            //Polyline polyline = entities.Find(x => x is Polyline) as Polyline;
            //UmUserMethod.SetImpliedSelection(new List<DBObject>() { circle, polyline });
            //if (!UmUserMethod.GetEntity(out MText mText)) return;
            //Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.SendStringToExecute("COMMANDLINE ", true, false, true);

        }
        [CommandMethod("BEAM")]
        public void BEAM()
        {
            List<string> jizhongLayers = new List<string>() { "梁集中标注", "梁集中标注竖向" };
            List<Entity> entities = UmUserMethod.SelectAllEntities<Entity>();
            entities = entities.FindAll(x => jizhongLayers.Contains(x.Layer));
            List<Line> lines = entities.FindAll(x => x is Line).Cast<Line>().ToList();
            List<DBText> texts = entities.FindAll(x => x is DBText).Cast<DBText>().ToList();
            Dictionary<Line, List<DBText>> valuePairs = new Dictionary<Line, List<DBText>>();
            foreach (Line line in lines)
            {
                valuePairs.Add(line, new List<DBText>());
            }
            foreach (var text in texts)
            {
                Line line = lines.OrderBy(x => x.GetClosestPointTo(text.Position, false).DistanceTo(text.Position)).ToList()[0];
                valuePairs[line].Add(text);
            }
            foreach (var item in valuePairs)
            {
                Line line = item.Key;
                List<DBText> dBTexts = item.Value;
                Point3d point = new Point3d();
                double dis = line.Length * 2;
                foreach (var dbtext in dBTexts)
                {
                    if (line.StartPoint.DistanceTo(dbtext.Position) < dis)
                    {
                        dis = line.StartPoint.DistanceTo(dbtext.Position);
                        point = line.StartPoint;
                    }
                    if (line.EndPoint.DistanceTo(dbtext.Position) < dis)
                    {
                        dis = line.EndPoint.DistanceTo(dbtext.Position);
                        point = line.EndPoint;
                    }
                }
                foreach (var dbtext in dBTexts)
                {
                    List<Point3d> points = PmPolylineMethod.GetPoint3ds(PmPolylineMethod.CreatePolylineByExtents3d(dbtext.GeometricExtents));
                    Point3d p = points.OrderBy(x => x.DistanceTo(dbtext.Position)).ToList()[3];
                    Line l1 = new Line(p, dbtext.Position);
                    Line l2 = new Line(l1.GetPointAtDist(l1.Length / 2), point);
                    EmEntityMethod.AddEntity(l1);
                    EmEntityMethod.AddEntity(l2);

                }
            }
        }
        public class MyBeam
        {
            public string Number { get; set; }
            public int Kua { get; set; }
            public double Width { get; set; }
            public double Height { get; set; }
            public bool IsTrue { get; set; }

            public void Mybeam(string text)
            {
                var ss = text.Split(' ');
                //if(ss)
            }
        }
        [CommandMethod("BBB")]
        public void BBB()
        {
            Extents3d extents = new Extents3d(new Point3d(), new Point3d());
            Extents3d extents1 = new Extents3d(new Point3d(5, 5, 0), new Point3d(10, 10, 0));
            extents.AddExtents(extents1);
            extents.Print();
        }
        [CommandMethod("SetXData")]
        public void SetXData()
        {
            Line line = new Line(new Point3d(0, 0, 0), new Point3d(100, 100, 0));
            XData.RegApp("xxx");
            XData.SetXData(line, "xxx", "aaa");
            EmEntityMethod.AddEntity(line);
        }
        [CommandMethod("GetXData")]
        public void GetXData()
        {
            string regName = "autoshikou";
            if (!UmUserMethod.GetEntity(out Polyline line, "1")) return;
            var sss = XData.GetXData(line, regName);
        }
        [CommandMethod("AddNum")]
        public void AddNum()
        {
            if (!UmUserMethod.GetInt(out int n, "请输入增量", 1)) return;
            if (!UmUserMethod.GetEntity(out DBText text, "请选择初始文字")) return;
            string input = text.TextString;
            string number = new string(input.Where(char.IsDigit).ToArray());
            if (int.TryParse(number, out int num))
            {
                while (true)
                {
                    num += n;
                    DBText dBText = text.KeLong();
                    dBText.TextString = input.Replace(number, num.ToString());
                    JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
                    {
                        dBText.Position = p;
                        e1.Add(dBText);
                    });
                    if (jig.IsStop()) break;
                }
            }
        }
        [CommandMethod("ShanDian")]
        public void ShanDian()
        {
            if (!UmUserMethod.SelectEntities(out List<Entity> entities)) return;
            Extents3d extents = EmEntityMethod.GetExtents3d(entities);
            Point3d p = extents.MinPoint;
            double width = extents.MaxPoint.X - extents.MinPoint.X;
            double height = extents.MaxPoint.Y - extents.MinPoint.Y;
            List<Line> lines = new List<Line>();
            MyTimer myTimer = new MyTimer(10, 100, (t, b) =>
            {
                int n = 36;
                List<int> nums = new List<int>();
                for (int i = 0; i < n; i++)
                {
                    nums.Add(i + 1);
                }
                Random random = new Random();
                while (n > 1)
                {
                    n--;
                    int k = random.Next(n + 1);
                    int value = nums[k];
                    nums[k] = nums[n];
                    nums[n] = value;
                }
                n = nums.Count;
                if (lines.Count > 0)
                {
                    lines.EraseEntities();
                    lines.Clear();
                }
                for (int i = 0; i < n; i++)
                {
                    Point3d point = p + new Vector3d(width * random.NextDouble(), height * random.NextDouble(), 0);
                    Line line = new Line(point, point + new Vector3d(nums[i], 0, 0));
                    //line.Rotation(p, Math.PI * 2 / n * i);
                    line.Rotation(point, Math.PI * 2 * random.NextDouble());
                    line.ColorIndex = 2;
                    lines.Add(line);
                    Line line1 = line.KeLong();
                    line1.Move(line.StartPoint, line.EndPoint);
                    line1.EndPoint = line1.StartPoint + line1.Delta * 0.2;
                    Line line2 = line1.KeLong();
                    line1.Rotation(line1.StartPoint, Math.PI / 6, true);
                    line2.Rotation(line1.StartPoint, Math.PI / 6, false);
                    lines.Add(line1);
                    lines.Add(line2);
                }
                lines.AddEntities();
                WCAD.Ed.UpdateScreen();

            });
        }
        //[CommandMethod("WWE")]
        public void WWE(Polyline pl)
        {
            int n = 100;
            double dis = pl.Length * 0.999 / n;
            TMTransientMethod tm = new TMTransientMethod();
            int num = 0;
            MyTimer myTimer = new MyTimer(10, n + 1, (t, b) =>
            {
                Point3d point = pl.GetPointAtDist(num * dis);
                Vector3d vector = pl.GetFirstDerivative(point);
                vector = vector.GetNormal() * dis;
                Line line = new Line(point, point + vector);
                line.ColorIndex = 2;
                Line line1 = line.KeLong();
                Line line2 = line.KeLong();
                line1.Rotation(point, Math.PI * 5 / 6, true);
                line2.Rotation(point, Math.PI * 5 / 6, false);
                tm.Clear();
                tm.Add(line1);
                tm.Add(line2);
                WCAD.Ed.UpdateScreen();
                num++;

                if (b)
                {
                    pl.AddEntity();
                    tm.Clear();
                }
            });

        }
        List<Entity> eeeee1 = new List<Entity>();
        List<Entity> eeeee2 = new List<Entity>();

        [CommandMethod("WEE")]
        public void WEE()
        {
            eeeee1 = new List<Entity>();
            eeeee2 = new List<Entity>();
            if (!UmUserMethod.GetPoint(out Point3d point, "选第一点")) return;
            if (!UmUserMethod.GetPoint(out Point3d point1, "选第一点", point)) return;
            Line line = new Line(point, point1);
            line.ColorIndex = 2;
            line.AddEntity();
            eeeee2.Add(line);
            List<Polyline> polylines = UmUserMethod.SelectAllEntities<Polyline>();
            Line line1 = line.Offset(50);
            Line line2 = line.Offset(-50);
            List<Point3d> ps1 = new List<Point3d>();
            List<Point3d> ps2 = new List<Point3d>();
            foreach (Polyline polyline in polylines)
            {
                eeeee1.Add(polyline.KeLong());
                Point3d p1 = polyline.IntersectWith(line1)[0];
                ps1.Add(p1);
                Point3d p2 = polyline.IntersectWith(line2)[0];
                ps2.Add(p2);
                List<Curve> curves = polyline.GetSplitCurves(p1, p2);
                Curve curve = curves.MaxBy(x => x.GetDistAtPoint(x.EndPoint)).First();
                eeeee2.Add(curve);
                curve.AddEntity();
                EmEntityMethod.EraseEntity(polyline);
            }
            Line l1 = new Line(ps1[0], ps1[1]);
            Line l2 = new Line(ps2[0], ps2[1]);
            l1.AddEntity();
            l2.AddEntity();
            eeeee2.Add(l1);
            eeeee2.Add(l2);


        }
        [CommandMethod("WEEE")]
        public void WEEE()
        {
            if (!UmUserMethod.GetEntity(out Line line, "选择连接线")) return;
            EmEntityMethod.AddEntities(eeeee1);
            EmEntityMethod.EraseEntities(eeeee2);
        }
        [CommandMethod("WWEE")]
        public void WWEE()
        {
            //if (!UmUserMethod.GetEntity(out Entity ent)) return;
            //var ss = ent.GetXData("SOUTH");
            //List<int> nums = new List<int>() { 1, 4, 2, 7, 8, 9, 22, 23, 35, 3 };
            StatusBar statusBar = Application.StatusBar;
            TrayItemCollection trayItemCollection = statusBar.TrayItems;

            TrayItem trayItem = new TrayItem();
            trayItem.ToolTipText = "123";
            trayItem.Icon = trayItemCollection[0].Icon;
            trayItemCollection.Add(trayItem);
            statusBar.Update();
            Line line = new Line(new Point3d(0, 0, 0), new Point3d(50, 50, 0));
            line.Layer = "0";
        }

        [CommandMethod("YC")]
        public void YC()
        {

            if (!UmUserMethod.GetEntity(out Polyline polyline)) return;
            List<Curve> curves = UmUserMethod.SelectAllEntities<Curve>();
            curves.Remove(polyline);
            double minx = polyline.GetPoint2dAt(3).X;
            double miny = polyline.GetPoint2dAt(3).Y;
            double maxx = polyline.GetPoint2dAt(1).X;
            double maxy = polyline.GetPoint2dAt(1).Y;
            double width = maxx - minx;
            double height = maxy - miny;
            pltodouble = new Dictionary<Polyline, List<double>>();
            foreach (var item in curves)
            {
                Polyline pl = new Polyline();
                List<double> doubles = new List<double>();
                int n = 1000;
                double dis = item.GetDistanceAtParameter(item.EndParam) / n;
                for (int i = 0; i < n; i++)
                {
                    Point2d point = item.GetPointAtDist(i * dis).ToPoint2d();
                    doubles.Add((point.X - minx) / width);
                    doubles.Add((point.Y - miny) / height);
                    pl.AddVertexAt(i, point, 0, 0, 0);
                }
                if (item.Closed)
                {
                    pl.Closed = true;
                }
                else
                {
                    Point2d point = item.EndPoint.ToPoint2d();
                    doubles.Add((point.X - minx) / width);
                    doubles.Add((point.Y - miny) / height);
                    pl.AddVertexAt(pl.NumberOfVertices, point, 0, 0, 0);
                }
                pltodouble.Add(pl, doubles);
                item.EraseEntity();
                pl.AddEntity();
            }
            polyline.EditEntity(() =>
            {
                polyline.Modified -= Polyline_Modified;
                polyline.Modified += Polyline_Modified;
            });
        }
        Dictionary<Polyline, List<double>> pltodouble = new Dictionary<Polyline, List<double>>();
        private void Polyline_Modified(object sender, EventArgs e)
        {
            Polyline pl = sender as Polyline;
            Line line1 = new Line(pl.GetPoint3dAt(0), pl.GetPoint3dAt(1));
            Line line2 = new Line(pl.GetPoint3dAt(3), pl.GetPoint3dAt(2));
            foreach (var item in pltodouble)
            {
                Polyline polyline = item.Key;
                List<double> doubles = item.Value;
                polyline.EditEntity(() =>
                {
                    for (int i = 0; i < doubles.Count / 2; i++)
                    {
                        double d1 = doubles[i * 2];
                        double d2 = doubles[i * 2 + 1];
                        Line line = new Line(line2.GetPointAtDist(d1 * line2.Length), line1.GetPointAtDist(d1 * line1.Length));
                        Point2d point = line.GetPointAtDist(d2 * line.Length).ToPoint2d();
                        polyline.SetPointAt(i, point);
                    }
                });
            }
        }
        [CommandMethod("YH")]
        public void YH()
        {
            List<Circle> circles = new List<Circle>();
            List<Vector3d> vectors = new List<Vector3d>();
            Vector3d vector = new Vector3d(1, 0, 0);
            Random random = new Random();

            for (int i = 0; i < 100; i++)
            {
                Circle circle = new Circle();
                circle.Radius = 1;
                circle.ColorIndex = Convert.ToInt32(1000 * random.NextDouble()) % 255;
                circles.Add(circle);
                vectors.Add(vector.RotateBy(Math.PI * 2 * random.NextDouble(), Vector3d.ZAxis));
            }

            TMTransientMethod tm = new TMTransientMethod(circles.Cast<Entity>().ToList());
            MyTimer myTimer = new MyTimer(10, 50, (t, b) =>
            {
                List<Circle> ccs = new List<Circle>();
                for (int i = 0; i < 100; i++)
                {
                    Circle circle = circles[i].KeLong();
                    circle.Center += vectors[i];
                    ccs.Add(circle);
                    vectors[i] *= 0.9;
                }
                circles.ForEach(x => x.Radius *= 0.8);

                tm.Update(circles);
                tm.Add(ccs);
                circles.InsertRange(0, ccs);
                WCAD.Ed.UpdateScreen();
                if (circles.Count > 500)
                {
                    for (int i = circles.Count - 1; i >= 500; i--)
                    {
                        tm.Remove(circles[i]);
                        circles.RemoveAt(i);
                    }
                }
                if (b)
                {
                    tm.Clear();
                    WCAD.Ed.UpdateScreen();
                }
            });


        }
        [CommandMethod("MH")]
        public void MH()
        {
            if (!UmUserMethod.SelectEntities(out List<Curve> curves)) return;
            Point3d point = curves.CenterPoint();
            List<List<Entity>> entities = new List<List<Entity>>();
            for (int i = 0; i < 90; i++)
            {
                entities.Add(new List<Entity>());
                foreach (var item in curves)
                {
                    Curve curve = item.KeLong();
                    curve.Rotation(point, Math.PI / 360 * (i + 1));
                    curve.Color = RgbColorMethod.RainbowAll(90 - i, 90);
                    curve.Transparency = new Transparency(Convert.ToByte(90 - (i + 1)));
                    entities[i].Add(curve);
                }
            }
            TMTransientMethod tm = new TMTransientMethod();
            int n = 0;
            int d = 1;
            MyTimer myTimer = new MyTimer(10, entities.Count * 2, (t, b) =>
            {
                if (d == 1)
                {
                    tm.Add(entities[n]);
                }
                else
                {
                    tm.Remove(entities[n]);
                }

                WCAD.Ed.UpdateScreen();
                if (n == entities.Count - 1 && d == 1)
                {
                    d = -1;
                    n += 1;
                }
                n += d;
            });
        }
        [CommandMethod("QLD")]
        public void QLD()
        {
            //double n = 0;
            //double num = 0;
            //if (!UmUserMethod.GetEntity(out DBText dBText)) return;
            //int m = 10000000;
            //for (int i = 0; i < m; i++)
            //{
            //    Random random = new Random();
            //    double d1 = random.NextDouble();
            //    double d2 = random.NextDouble();
            //    if (d1 > d2) (d1, d2) = (d2, d1);
            //    if (d1 == d2) continue;
            //    if (d1 == 0) continue;
            //    if (d2 == 1) continue;
            //    double l1 = d1;
            //    double l2 = d2 - d1;
            //    double l3 = 1 - d2;
            //    List<double> ls = new List<double>() { l1, l2, l3 };
            //    ls.Sort();
            //    num++;
            //    if (ls[0] + ls[1] > ls[2]) n++;
            //}
            //dBText.EditEntity(() => dBText.TextString = m.ToString() +"次的概率为" + (n * 100 / num).ToString("0.00") + "%");
            if (!UmUserMethod.GetPoint(out Point3d p1)) return;
            Circle circle1 = new Circle
            {
                Center = p1,
                Radius = 1,
                ColorIndex = 1
            };
            circle1.AddEntity();
            if (!UmUserMethod.GetPoint(out Point3d p2)) return;
            Circle circle2 = new Circle
            {
                Center = p2,
                Radius = 1,
                ColorIndex = 1
            };
            circle2.AddEntity();
            List<Line> lines = UmUserMethod.SelectAllEntities<Line>();
            Line line = lines.Find(x => x.GetClosestPointTo(p1, false).DistanceTo(p1) < 0.01 && x.GetClosestPointTo(p2, false).DistanceTo(p2) < 0.01);


            if (line == null) return;
            p1 = line.GetClosestPointTo(p1, false);
            p2 = line.GetClosestPointTo(p2, false);
            if (p1.DistanceTo(line.StartPoint) > p2.DistanceTo(line.StartPoint))
            {
                (p1, p2) = (p2, p1);
            }
            Line l1 = new Line(p1, line.StartPoint);
            l1.ColorIndex = 2;
            l1.AddEntity();
            Line l2 = new Line(p2, line.EndPoint);
            l2.ColorIndex = 2;
            l2.AddEntity();
            Line l3 = new Line(p1, p2);
            l3.ColorIndex = 2;
            l3.AddEntity();
            double d1 = Math.PI * 2;
            double d2 = Math.PI * 2;
            Vector3d v1 = Vector3d.ZAxis;
            Vector3d v2 = -Vector3d.ZAxis;

            if (l1.Length + l2.Length > l3.Length)
            {
                Circle c1 = new Circle()
                {
                    Center = p1,
                    Radius = l1.Length
                };
                Circle c2 = new Circle()
                {
                    Center = p2,
                    Radius = l2.Length
                };
                Point3d p = c1.IntersectWith(c2)[0];
                Line l11 = new Line(p1, p);
                Line l22 = new Line(p2, p);
                d1 = l1.Delta.GetAngleTo(l11.Delta, Vector3d.ZAxis);
                double d11 = l1.Delta.GetAngleTo(l11.Delta, -Vector3d.ZAxis);
                if (d11 < d1)
                {
                    d1 = d11;
                    v1 = -Vector3d.ZAxis;
                }
                else
                {
                    v1 = Vector3d.ZAxis;
                }
                d2 = l2.Delta.GetAngleTo(l22.Delta, Vector3d.ZAxis);
                double d22 = l2.Delta.GetAngleTo(l22.Delta, -Vector3d.ZAxis);
                if (d22 < d2)
                {
                    d2 = d22;
                    v1 = -Vector3d.ZAxis;
                }
                else
                {
                    v1 = Vector3d.ZAxis;
                }
            }
            int n = 100;
            d1 /= Convert.ToDouble(n);
            d2 /= Convert.ToDouble(n);
            int i = 0;
            MyTimer myTimer = new MyTimer(10, n, (t, b) =>
            {
                l1.EditEntity(() => l1.Rotation(p1, d1, v1.Z < 0));
                l2.EditEntity(() => l2.Rotation(p2, d2, v2.Z < 0));
                i++;
                WCAD.Ed.UpdateScreen();

            });
        }
        [CommandMethod("FZ")]
        public void FZ()
        {
            if (!UmUserMethod.GetPoint(out Point3d point)) return;
            List<DBPoint> dBPoints = new List<DBPoint>();
            int max = 1000;
            for (int j = 0; j < max; j++)
            {
                DBPoint dBPoint = new DBPoint();
                dBPoint.Position = point;
                dBPoint.Color = RgbColorMethod.RainbowAll(j, max);
                dBPoints.Add(dBPoint);
            }
            Random random = new Random();
            Vector3d vector = new Vector3d(1, 0, 0);
            TMTransientMethod tm = new TMTransientMethod(dBPoints.Cast<Entity>().ToList());
            MyTimer myTimer = new MyTimer(10, 10000, (t, b) =>
            {
                List<Entity> entities = UmUserMethod.SelectAllEntities<Entity>();
                if (entities.Count == 0)
                {
                    t.Stop();
                    tm.Clear();
                    WCAD.Ed.UpdateScreen();
                }
                foreach (var item in dBPoints)
                {
                    Vector3d v = new Vector3d();
                    while (true)
                    {
                        v = vector.RotateBy(Math.PI * 2 * random.NextDouble(), Vector3d.ZAxis);
                        v *= 50 * random.NextDouble();
                        Line line = new Line(item.Position, item.Position + v);
                        if (entities.All((x) => x.IntersectWith(line).Count == 0))
                        {
                            break;
                        }

                    }
                    item.Position += v;
                }
                tm.Update(dBPoints);
                WCAD.Ed.UpdateScreen();
            });
            //int i = 10;
            //while (true)
            //{
            //    List<Entity> entities = UmUserMethod.SelectAllEntities<Entity>();
            //    if (UmUserMethod.GetInt(out int ii, "设置温度，按0结束", i))
            //    {
            //        i = ii;
            //    }
            //    if (i == 0) break;
            //    foreach (var item in dBPoints)
            //    {
            //        Vector3d v = new Vector3d();
            //        int m = 0;
            //        while (true)
            //        {
            //            v = vector.RotateBy(Math.PI * 2 * random.NextDouble(), Vector3d.ZAxis);
            //            v *= i * random.NextDouble();
            //            Line line = new Line(item.Position, item.Position + v);
            //            if (entities.All(x => x.IntersectWith(line).Count == 0))
            //            {
            //                break;
            //            }
            //            m++;
            //            if (m == 100)
            //            {
            //                v = new Vector3d(0, 0, 0);
            //                break;
            //            }
            //        }
            //        item.Position += v;
            //    }
            //    tm.Update(dBPoints);
            //}
            //tm.Clear();
            //WCAD.Ed.UpdateScreen();
        }
        [CommandMethod("JDT")]
        public void JDT()
        {
            TMTransientMethod tm = new TMTransientMethod();
            Line line = new Line(new Point3d(), new Point3d(100, 0, 0));
            line.ColorIndex = 2;
            tm.Add(line);
            Line l = new Line(new Point3d(), new Point3d(0, 0, 0));
            l.ColorIndex = 2;
            l.LineWeight = LineWeight.LineWeight200;
            tm.Add(l);
            DBText dBText = new DBText();
            dBText.Position = new Point3d(0, 2, 0);
            dBText.TextString = "0%";
            dBText.ColorIndex = 2;
            tm.Add(dBText);
            int n = 1;
            MyTimer myTimer = new MyTimer(20, 100, (t, b) =>
            {
                l.EndPoint = new Point3d(n, 0, 0);
                dBText.Position = new Point3d(n, dBText.Position.Y, 0);
                dBText.TextString = n.ToString() + "%";
                tm.Update(l);
                tm.Update(dBText);
                n++;
                if (b)
                {
                    //tm.Clear();
                }
                WCAD.Ed.UpdateScreen();
            });
        }
        [CommandMethod("WLK")]
        public void WLK()
        {
            //if (!UmUserMethod.SelectEntities(out List<Curve> curves)) return;
            //Extents3d extents = curves.GetExtents3d();
            //double width=extents.MaxPoint.X- extents.MinPoint.X;
            //double heitht=extents.MaxPoint.Y- extents.MinPoint.Y;
            //double num = 100;
            //double w=width/num;
            //double h=heitht/num;
            Line line1 = new Line(new Point3d(), new Point3d(10, 0, 0));
            Line line2 = new Line(new Point3d(20, 0, 0), new Point3d(30, 1, 0));
            line1.JoinEntity(line2);
            line1.AddEntity();
        }
        [CommandMethod("LLinq")]
        public void LLinq()
        {
            //FirstOrDefault 第一个满足条件的元素
            //Find 第一个满足条件的元素（List的方法）
            //Where 所有满足条件的元素
            //FindAll 所有满足条件的元素（List的方法）
            //Select 返回每个元素进行某种操作后的集合
            //Cast 返回每个元素转类型后的集合
            //Any 如果有任一元素满足条件
            //All 如果所有元素满足条件
            //OrderBy 排序
            //GroupBy 分组
            //Aggregate 累加
            //Max 取最大的数
            //Min 取最小的数
            //MaxBy 取最大数的那几个元素(LineMore)
            //MinBy 取最小数的那几个元素(LineMore)
            //Except 两个List的差值
            //Distinct 去重
            List<int> nums1 = new List<int>() { 1, 3, 2, 6, 1, 2, 2, 3 };
            //List<int> nums2 = new List<int>() { 1, 4, 5 };
            //var nums3=nums1.Except(nums2);
            var nums3 = nums1.Distinct();
            foreach (var item in nums3)
            {
                WCAD.Ed.WriteMessage(item.ToString());
            }
            //int n = nums.Aggregate((x,y) => x*y);
            //WCAD.Ed.WriteMessage(n.ToString());
            //nums=nums.OrderBy(x =>Math.Abs(x)).ThenBy(x=>x).ToList();
            //var ss = nums.Where(x => x > 1);
            //if (!UmUserMethod.SelectEntities(out List<Circle> cirs)) return;
            //var ss = cirs.MinBy(x => x.Radius);
            //foreach (var item in ss)
            //{
            //    DBText dBText = new DBText();
            //    dBText.TextString = "小";
            //    dBText.Position = item.Center;
            //    dBText.AddEntity();
            //}
            ////ss.EditEntities(() =>
            ////{
            ////    ss.ForEach(x => x.ColorIndex = 2);
            ////});
            //int n = 1;
            //foreach (var item in cirs)
            //{
            //    DBText dBText = new DBText();
            //    dBText.TextString = n.ToString();
            //    dBText.Position = item.Center;
            //    dBText.AddEntity();
            //    n++;
            //}

        }
        [CommandMethod("YJ")]
        public void YJ()
        {
            if (!UmUserMethod.GetEntity(out BlockReference bl)) return;
            BmBlcokMethod.IsXCBlcok(bl);
            return;
            if (!UmUserMethod.GetEntity(out Polyline pl)) return;
            BmBlcokMethod.SetXC(bl, pl);
        }
        [CommandMethod("YYJ")]
        public void YYJ()
        {
            if (!UmUserMethod.SelectEntities(out List<BlockReference> blocks)) return;
            ExcelMethod.OpenExcel(@"C:\Users\Administrator\Desktop\新建 XLS 工作表.xls", true);
            List<string> strs = new List<string>();
            for (int i = 0; i < 100; i++)
            {
                object obj = ExcelMethod.GetCell(1, i + 1);
                if (obj == null) break;
                strs.Add(obj.ToString());
            }

            int row = 2;
            foreach (var item in blocks)
            {
                var ss = item.GetAtt();
                if (ss.Count > 0)
                {
                    foreach (var att in ss)
                    {
                        for (int i = 0; i < strs.Count; i++)
                        {
                            if (strs[i].Contains(att.Key))
                            {
                                ExcelMethod.SetCell(row, i + 1, att.Value);
                                Thread.Sleep(100);
                                break;
                            }
                        }

                    }
                    row++;
                }
            }
            //ExcelMethod.Quit();
        }
        [CommandMethod("YYJJ")]
        public void YYJJ()
        {
            if (!UmUserMethod.GetEntity(out Arc arc)) return;
            if (!UmUserMethod.GetEntity(out Polyline polyline)) return;
            List<Line> lines = polyline.ExplodePolyline().Cast<Line>().ToList();
            List<Polyline> pls = new List<Polyline>();
            foreach (var item in lines)
            {
                if (item.Delta.Y == 0)
                {
                    Polyline pl = arc.OffsetPl(item.Length / 2);
                    if (item.Delta.X > 0)
                    {
                        pl.Rotation(pl.CenterPoint(), Math.PI);
                    }
                    pls.Add(pl);
                }
                else if (item.Delta.Y > 0)
                {
                    Extents3d extents = new Extents3d(new Point3d(0, 0, 0), new Point3d(arc.Length, item.Length, 0));
                    pls.Add(PmPolylineMethod.CreatePolylineByExtents3d(extents));
                }
            }
            double h = 0;
            foreach (var item in pls)
            {
                double height = item.GetHeight();
                item.Move(item.CenterPoint(), new Point3d(0, h + height / 2, 0));
                h = item.GeometricExtents.MaxPoint.Y + 100;
            }
            JigJig jig = new JigJig(new Point3d(), (p, e1, e2) =>
            {
                foreach (var item in pls)
                {
                    var ss = item.KeLong();
                    ss.Move(new Point3d(), p);
                    e1.Add(ss);
                }
            });
        }
        [CommandMethod("CH")]
        public void CH()
        {

        }
        [CommandMethod("Demo11")]
        public void Demo11()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            PromptEntityResult per = ed.GetEntity("选择动态块");
            if (per.Status == PromptStatus.OK)
            {
                ObjectId id = per.ObjectId;
                using (Transaction tran = db.TransactionManager.StartTransaction())
                {
                    BlockReference block = id.GetObject(OpenMode.ForWrite) as BlockReference;
                    DynamicBlockReferencePropertyCollection dynProperties = block.DynamicBlockReferencePropertyCollection;

                    foreach (DynamicBlockReferenceProperty property in dynProperties)
                    {
                        if (property.ReadOnly)
                        {
                            continue;
                        }
                        string name = property.PropertyName;

                        if (name == "长")
                        {
                            property.Value = 500.0;
                        }
                        if (name == "宽")
                        {
                            property.Value = 400.0;
                        }
                    }
                    tran.Commit();
                }

            }
        }
        [CommandMethod("Demo12")]
        public void Demo12()
        {
            Line line1 = new Line(new Point3d(0, 0, 0), new Point3d(10, 10, 0));
            Line line2 = new Line(new Point3d(0, 0, 0), new Point3d(10, 20, 0));
            WCAD.StartTime();
            for (int i = 0; i < 100000; i++)
            {
                Xiangjiao1(line1, line2);
            }
            WCAD.ShowTime();
            for (int i = 0; i < 100000; i++)
            {
                Xiangjiao2(line1, line2);
            }
            WCAD.ShowTime();
            for (int i = 0; i < 100000; i++)
            {
                Xiangjiao3(line1, line2);
            }
            WCAD.ShowTime();
        }
        public bool Xiangjiao1(Line line1, Line line2)
        {
            Point3dCollection pos = new Point3dCollection();
            line1.IntersectWith(line2, Intersect.OnBothOperands, pos, IntPtr.Zero, IntPtr.Zero);
            return pos.Count > 0;
        }
        public bool Xiangjiao2(Line line1, Line line2)
        {
            var l1 = line1.GetGeCurve();
            var l2 = line2.GetGeCurve();
            var ss = l1.GetClosestPointTo(l2);

            return ss[0].Point.DistanceTo(ss[1].Point) == 0;
        }
        public bool Xiangjiao3(Line line1, Line line2)
        {
            double k1 = (line1.EndPoint.Y - line1.StartPoint.Y) / (line1.EndPoint.X - line1.StartPoint.X);
            double b1 = line1.StartPoint.Y - k1 * line1.StartPoint.X;
            double k2 = (line2.EndPoint.Y - line2.StartPoint.Y) / (line2.EndPoint.X - line2.StartPoint.X);
            double b2 = line2.StartPoint.Y - k2 * line2.StartPoint.X;
            double y = (b2 - b1) / (k1 - k2);
            double d1 = (y - line1.StartPoint.Y) * (y - line1.EndPoint.Y);
            double d2 = (y - line2.StartPoint.Y) * (y - line2.EndPoint.Y);
            return d1 <= 0 && d2 <= 0;
        }
        [CommandMethod("Demo111")]
        public void Demo111()
        {
            if (!UmUserMethod.GetDouble(out double width, "输入宽度")) return;
            if (!UmUserMethod.SelectEntities(out List<Polyline> pls)) return;
            foreach (var item in pls)
            {
                Extents3d extents = item.GeometricExtents;
                double mid = extents.MinPoint.X / 2 + extents.MaxPoint.X / 2;
                double w = extents.MaxPoint.X - extents.MinPoint.X;
                w = (width - w) / 2;
                item.EditEntity(() =>
                {
                    for (int i = 0; i < item.NumberOfVertices; i++)
                    {
                        Point2d point = item.GetPoint2dAt(i);
                        double ww = 0;
                        if (point.X < mid)
                        {
                            ww = -w;
                        }
                        else
                        {
                            ww = w;
                        }
                        item.SetPointAt(i, point + new Vector2d(ww, 0));
                    }
                });
            }
        }
        [CommandMethod("Biaozhu")]
        public void Biaozhu()
        {
            //if (!UmUserMethod.GetEntity(out Circle cir, "请选择孔")) return;
            //if (!UmUserMethod.GetEntity(out Line line, "请选择边线")) return;
            //if (!UmUserMethod.GetDouble(out double dis, "请输入距离")) return;
            //Point3d point = line.GetClosestPointTo(cir.Center, false);
            //Vector3d vector = cir.Center - point;
            //cir.EditEntity(() => cir.Center = point + vector.GetNormal() * dis);

            //var dim= DmDimensionMethod.AddRotatedDimension(point, cir.Center, dis / 3);
            //dim.AddEntity();
            //Vector3d vector = new Vector3d(1, 2, 3);
            //double d = vector.LengthSqrd;
            //WCAD.Ed.WriteMessage(d.ToString());
            //Polyline pl = new Polyline();

            //string dxfname = RXObject.GetClass(typeof(Polyline)).DxfName;
            //if (!UmUserMethod.GetEntity(out Circle circle)) return;
            //double r = circle.Radius;
            //WCAD.Ed.WriteMessage(r.ToString());
            //Circle.GetClass
            //WCAD.Doc.CapturePreviewImage(200, 200).Save(@"C:\Users\Administrator\Desktop\acad.png");
            //if (!UmUserMethod.GetEntity(out BlockReference block)) return;
            //List<string> names= block.GetDynBlockValues();
            //if (block.SetDynBlockValues(names[2]))
            //{
            //    //执行接下来操作
            //}
            //string input = "0.02";
            //string output = input.TrimStart('0');
            //WCAD.Ed.WriteMessage(output);
            if (!UmUserMethod.GetEntity(out Entity ent)) return;


            List<DBText> dBTexts = new List<DBText>();
            Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();
            foreach (var item in dBTexts)
            {
                if (keyValuePairs.ContainsKey(item.TextString))
                {
                    keyValuePairs[item.TextString]++;
                }
                else
                {
                    keyValuePairs[item.TextString] = 1;
                }
            }
            dBTexts.Clear();
            foreach (var item in keyValuePairs)
            {
                DBText dBText = new DBText();
                dBText.TextString = item.Key + "*" + item.Value.ToString();
                dBTexts.Add(dBText);
            }
        }
        [CommandMethod("RREC")]
        public void RREC()
        {
            if (!UmUserMethod.GetPoint(out Point3d p1)) return;
            if (!UmUserMethod.GetPoint(out Point3d p2, "", p1)) return;
            Line line = new Line(p1, p2);

            JigPromptPointOptions jppo = new JigPromptPointOptions();
            jppo.BasePoint = p1;
            jppo.UseBasePoint = true;
            JigJig jig = new JigJig(p1, (p, e1, e2) =>
            {
                jppo.BasePoint = line.GetClosestPointTo(p, true);
                Vector3d vector = p - line.GetClosestPointTo(p, true);
                Polyline pl = PmPolylineMethod.CreatePolyline(new List<Point3d>() { p1, p2, p2 + vector, p1 + vector });
                e1.Add(DmDimensionMethod.AddRotatedDimension(p1, p2, 10));
                if (vector.Length > 0)
                {
                    e1.Add(DmDimensionMethod.AddRotatedDimension(p2, p2 + vector, 20));
                }
                e1.Add(pl);
            }, jppo);
            var ss = WCAD.Ed.Drag(jig).Status;
            if (ss == PromptStatus.OK)
            {
                jig.GetEntities().AddEntities();
            }
        }
        [CommandMethod("RRE")]
        public void RRE()
        {
            if (!UmUserMethod.GetEntity(out Line line)) return;
            if (!UmUserMethod.GetEntity(out BlockReference bl)) return;
            Point3dCollection pos = new Point3dCollection();
        }
        [CommandMethod("GK")]
        public void GK()
        {
            Point3d point = new Point3d(0, 0.5, 0);
            List<DBPoint> dBPoints = new List<DBPoint>();
            double x = 0;
            double y = 0;
            JigJig jig = new JigJig(point, (p, e1, e2) =>
            {
                x = p.X;
                y = 0.25 + Math.Pow(x, 2);
                Circle circle = new Circle();
                circle.Center = new Point3d(x, y, 0);
                circle.ColorIndex = 2;
                circle.Radius = 0.05;
                circle.LineWeight = LineWeight.LineWeight050;
                e2.Add(circle);
                Line line1 = new Line(circle.Center, point);
                line1.ColorIndex = 1;
                line1.LineWeight = LineWeight.LineWeight020;
                Line line2 = new Line(circle.Center, new Point3d(x, 0, 0));
                line2.ColorIndex = 1;
                line2.LineWeight = LineWeight.LineWeight020;
                e2.Add(line1);
                e2.Add(line2);
                if (dBPoints.All(c => c.Position.DistanceTo(circle.Center) > 0.0001))
                {
                    dBPoints.Add(new DBPoint() { Position = circle.Center });
                }
                e1.AddRange(dBPoints);
            });
            JigJig jigJig = new JigJig(new Point3d(x, y, 0), (p, e1, e2) =>
            {
                if (p.X - x != 0)
                {
                    double k = (p.Y - y) / (p.X - x);
                    double x1 = (k + Math.Sqrt(Math.Pow(k, 2) - 4 * (k * x - x * x))) / 2;
                    double x2 = (k - Math.Sqrt(Math.Pow(k, 2) - 4 * (k * x - x * x))) / 2;
                    double xx = Math.Abs(x1 - x) > Math.Abs(x2 - x) ? x1 : x2;
                    double yy = xx * xx + 0.25;
                    Point3d p1 = new Point3d(x, y, 0);
                    Point3d p2 = new Point3d(xx, yy, 0);

                    if (p1.DistanceTo(p2) > 0.1)
                    {
                        k = -1 / k;
                        double b = yy - xx * k;
                        double xx1 = (k + Math.Sqrt(Math.Pow(k, 2) - 4 * (-b + 0.25))) / 2;
                        double xx2 = (k - Math.Sqrt(Math.Pow(k, 2) - 4 * (-b + 0.25))) / 2;
                        double xxx = Math.Abs(xx1 - xx) > Math.Abs(xx2 - xx) ? xx1 : xx2;
                        double yyy = xxx * xxx + 0.25;
                        Point3d p3 = new Point3d(xxx, yyy, 0);
                        Point3d p4 = p3 + (p1 - p2);
                        Polyline polyline = PmPolylineMethod.CreatePolyline(new List<Point3d>() { p1, p2, p3, p4 });
                        DBText text = new DBText()
                        {
                            TextString = "周长：" + polyline.Length.ToString("0.00"),
                            Height = polyline.GetHeight() / 10,
                            ColorIndex = 2,
                            Justify = AttachmentPoint.MiddleCenter,
                            AlignmentPoint = polyline.GeometricExtents.MinPoint + new Vector3d(polyline.GetWidth() / 2, polyline.GetHeight() / 2, 0)
                        };
                        text.SetDatabaseDefaults(WCAD.Db);
                        text.AdjustAlignment(WCAD.Db);
                        e2.Add(text);
                        e1.Add(polyline);
                        if (dBPoints.All(c => c.Position.DistanceTo(p2) > 0.0001))
                        {
                            dBPoints.Add(new DBPoint() { Position = p2 });
                        }
                        if (dBPoints.All(c => c.Position.DistanceTo(p3) > 0.0001))
                        {
                            dBPoints.Add(new DBPoint() { Position = p3 });
                        }
                        e2.AddRange(dBPoints);
                    }
                }

            });
        }
        [CommandMethod("AARC")]
        public void AARC()
        {
            if (!UmUserMethod.GetEntity(out Arc arc)) return;
            Polyline polyline = new Polyline();
            polyline.ColorIndex = 2;
            polyline.AddVertexAt(0, arc.StartPoint.ToPoint2d(), Math.Tan(arc.TotalAngle / 4), 0, 0);
            polyline.AddVertexAt(1, arc.EndPoint.ToPoint2d(), 0, 0, 0);
            polyline.AddEntity();
        }
        [CommandMethod("AAARC")]
        public void AAARC()
        {
            List<List<Point3d>> points = new List<List<Point3d>>();
            points.Add(new List<Point3d>());
            points[0].Add(new Point3d(1, 2, 3));
            points[0].Add(new Point3d(4, 5, 6));
            points[0].Add(new Point3d(7, 8, 9));
            List<List<Point3d>> ps2 = points.ToList();
            ps2[0][0] += new Vector3d(1, 1, 1);
        }
    }
}


